mlin956
mlin956

Reputation: 365

How to animate text color of a UILabel like a progress bar

I'm trying to change the text color of a UILabel progressively from left to right. I found I can use UIView's animation:

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

But the question is there isn't an option for my case: progressively from left to right.

Then I found a way to change the text color letter by letter by calling:

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

But the question here is that I want the animation be more like letter by letter but each letter has animation as well, like there are two labels with different colors placed in the same position (black covers red) and just animate a mask from left to right to hide the black label so that the red label shows progressively.

So is there a way to achieve this?

Upvotes: 0

Views: 750

Answers (1)

trungduc
trungduc

Reputation: 12144

To achieve it, follow below steps:

  • Create 2 UILabel (trackLabel and progressLabel).
  • trackLabel have blackColor and progressLabel have redColor.
  • Make progressLabel overlap trackLabel, same leading, top and bottom.
  • Give trackLabel full width with text and progressLabel 0 width.
  • Set progressLabel.lineBreakMode = NSLineBreakByClipping;
  • When you need to animate progress, increase width of progressLabel.

For more detail, you can check my demo project.

enter link description here

Upvotes: 6

Related Questions