如何像进度条一样为 UILabel 的文本颜色设置动画

mli*_*956 0 animation text objective-c uilabel ios

我正在尝试从左到右逐步更改 UILabel 的文本颜色。我发现我可以使用 UIView 的动画:

[UIView transitionWithView:_label duration:1 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
    _label.textColor = [UIColor redColor];
} completion:nil];
Run Code Online (Sandbox Code Playgroud)

但问题是我的情况没有选择:从左到右逐渐进行。

然后我找到了一种通过调用以下命令来逐个字母地更改文本颜色的方法:

[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(yourSelector) userInfo:nil repeats:NO];

- (void)yourSelector
{
    [_string setAttributes:@{NSForegroundColorAttributeName: [UIColor redColor]} range:NSMakeRange(_index, 1)];
    [_label setAttributedText:_string];
    _index++;
}
Run Code Online (Sandbox Code Playgroud)

但这里的问题是,我希望动画更像是一个字母一个字母,但每个字母也有动画,就像有两个不同颜色的标签放置在同一位置(黑色覆盖红色),然后从左到右对蒙版进行动画处理向右隐藏黑色标签,以便红色标签逐渐显示。

那么有没有办法实现这一点呢?

tru*_*duc 5

要实现它,请按照以下步骤操作:

  • 创建 2 UILabel(trackLabelprogressLabel)。
  • trackLabelblackColorprogressLabelredColor
  • 使progressLabel重叠trackLabel,相同的引导,顶部和底部。
  • 给出trackLabel文本的全宽和progressLabel0 宽度。
  • progressLabel.lineBreakMode = NSLineBreakByClipping;
  • 当您需要动画进度时,增加 的宽度progressLabel

有关更多详细信息,您可以查看我的演示项目

在此输入链接描述