gpt4 book ai didi

ios - 带动画的 NSMutableAttributedString 删除线

转载 作者:搜寻专家 更新时间:2023-10-30 20:19:37 25 4
gpt4 key购买 nike

- (void)setStrokeLabel:(BOOL)strokeLabel
{
_strokeLabel = strokeLabel;

if (_strokeLabel) {
_timer = [NSTimer scheduledTimerWithTimeInterval:0.4 target:self selector:@selector(setStrokeThrough) userInfo:nil repeats:NO];
} else {
[self cancelStrokeThrough];
}
}

- (void)setStrokeThrough
{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];

for (NSUInteger i = 1; i <= [attributedString length]; i++) {
[attributedString addAttribute:NSStrikethroughStyleAttributeName
value:[NSNumber numberWithInt:1]
range:NSMakeRange(0, i)];
self.attributedText = attributedString;
}
}

- (void)cancelStrokeThrough
{
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
[attributedString removeAttribute:NSStrikethroughStyleAttributeName
range:NSMakeRange(0, [attributedString length])];
self.attributedText = attributedString;

}

我想制作 删除线 动画,比如 todo done 动画。当我为它设置计时器时,计时器只处理如何逐个字母地显示行程?

最佳答案

这里有两个函数可以完成这项工作。

    BOOL setStrokethrough(UILabel *label, NSRange range)
{
if (range.location >= [label.attributedText length])
return FALSE;

if (range.location + range.length > [label.attributedText length])
range.length = [label.attributedText length] - range.location;

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:label.attributedText];

[attributedString addAttribute:NSStrikethroughStyleAttributeName
value:@(NSUnderlineStyleSingle)
range:range];

label.attributedText = attributedString;
return TRUE;
}

-(void)animateSetStrokethroughDuration:(float)duration
{
__block float const stepDuration = 0.1;
float steps = duration / stepDuration;
__block NSRange range = NSMakeRange(0, ceil((float)[self.label.attributedText length] / steps));

void (^__block fn)();
void (^__block __weak weakfn)();

weakfn = fn = ^(){
if (!setStrokethrough(self.label, range))
return;
range = NSMakeRange(range.location + range.length, range.length);
[self performBlock:weakfn afterDelay:stepDuration];
};
fn();
}

注意事项

  1. 为了限制动画时间,我按角色 block 制作动画,而不是按角色制作动画。字符串越长,字符 block 越长。
  2. __block __weak 业务在 here 中解释
  3. self performBlock 是 Mike Ash 对 NSObject 的扩展和还有here
  4. 代码假定您定义了 self.label 成员

关于ios - 带动画的 NSMutableAttributedString 删除线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15741567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com