【问题标题】:How to animate text color of a UILabel like a progress bar如何像进度条一样为 UILabel 的文本颜色设置动画
【发布时间】:2018-03-29 00:55:44
【问题描述】:

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

[UIView transitionWithView:_label duration:1 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
    _label.textColor = [UIColor redColor];
} completion:nil];

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

然后我找到了一种通过调用逐字母更改文本颜色的方法:

[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++;
}

但这里的问题是,我希望动画更像一个字母一个字母,但每个字母也有动画,就像有两个不同颜色的标签放置在同一位置(黑色覆盖红色)并且只是为蒙版制作动画从左到右隐藏黑色标签,使红色标签逐渐显示。

那么有没有办法做到这一点?

【问题讨论】:

  • 啊,你想让它像一个进度条吗?不是“逐个字母”

标签: ios objective-c animation text uilabel


【解决方案1】:

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

  • 创建 2 个UILabeltrackLabelprogressLabel)。
  • trackLabelblackColorprogressLabelredColor
  • 使progressLabel 重叠trackLabel,相同的前导,顶部和底部。
  • trackLabel 提供全宽与文本和progressLabel 0 宽度。
  • 设置progressLabel.lineBreakMode = NSLineBreakByClipping;
  • 当您需要动画进度时,增加progressLabel的宽度。

更多详情可以查看my demo project

【讨论】:

  • 我得到的问题是,当我需要在左/右添加一些填充并使其居中对齐时,上面的标签无法将其文本定位在底部标签的正上方
  • 在这种情况下,您应该计算文本宽度,为进度标签提供合适的前导约束。
猜你喜欢
  • 2013-10-10
  • 1970-01-01
  • 1970-01-01
  • 2011-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多