Вопрос задавался давно, но здесь идет.
Как уже говорилось выше, textColor для UILabel
не может быть анимирован.Полезный трюк состоит в том, чтобы динамически создать в коде другой UILabel
, с такими же атрибутами и положением, но с цветом назначения.Вы анимируете альфа новой UILabel
от 0,0 до 1,0, поэтому создается впечатление, что текстовый цвет оригинальной UILabel анимирован.Когда анимация будет завершена, вы можете удалить одну из меток.
Вот пример метода уровня класса, который на короткое время меняет свой текст на TextColor и возвращает обратно.
+(void)colorizeLabelForAWhile:(UILabel *)label withUIColor:(UIColor *)tempColor animated:(BOOL)animated
{
// We will:
// 1) Duplicate the given label as a temporary UILabel with a new color.
// 2) Add the temp label to the super view with alpha 0.0
// 3) Animate the alpha to 1.0
// 4) Wait for awhile.
// 5) Animate back and remove the temporary label when we are done.
// Duplicate the label and add it to the superview
UILabel *tempLabel = [[UILabel alloc] init];
tempLabel.textColor = tempColor;
tempLabel.font = label.font;
tempLabel.alpha = 0;
tempLabel.textAlignment = label.textAlignment;
tempLabel.text = label.text;
[label.superview addSubview:tempLabel];
tempLabel.frame = label.frame;
// Reveal the temp label and hide the current label.
if (animated) [UIView beginAnimations:nil context:nil];
tempLabel.alpha = 1;
label.alpha = 0;
if (animated) [UIView commitAnimations];
// Wait for while and change it back.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, FOR_AWHILE_TIME*NSEC_PER_SEC), dispatch_get_main_queue(), ^{
if (animated) {
// Change it back animated
[UIView animateWithDuration:0.5 animations:^{
// Animate it back.
label.alpha = 1;
tempLabel.alpha = 0;
} completion:^(BOOL finished){
// Remove the tempLabel view when we are done.
[tempLabel removeFromSuperview];
}];
} else {
// Change it back at once and remove the tempLabel view.
label.alpha = 1.0;
[tempLabel removeFromSuperview];
}
});
}