我正在尝试使UILabel中的文本颜色动画脉冲,从[黑色]到[白色]再到[黑色]并重复。
- (void)timerFlash:(NSTimer *)timer {
[[self navTitle] setTextColor:[[UIColor whiteColor] colorWithAlphaComponent:0.0]];
[UIView animateWithDuration:1
delay:0
options:UIViewAnimationOptionAllowUserInteraction
animations:^{[[self navTitle] setTextColor:[[UIColor whiteColor] colorWithAlphaComponent:1.0]];}
completion:nil];
}
.
[self setFadeTimer:[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFlash:) userInfo:nil repeats:YES]];
首先,我对我的方法不确定,我的计划(如上所述)是设置一个动画块,并使用重复的NSTimer调用它,直到取消。其次,我的第二个问题(如上所述)是,我正在从黑色(alpha 0)动画到白色(alpha 1),但我不知道如何再次动画回黑色,使动画无缝循环。
本质上,我想要的是在UILabel上脉冲文本颜色,直到用户按下按钮继续。
编辑_001:
我遇到麻烦,因为您无法动画化[UILabel setColor:],但是您可以动画化[UILabel setAlpha:],所以我将尝试一下。
编辑_002:
- (void)timerFlash:(NSTimer *)timer {
[[self navTitle] setAlpha:0.5];
[UIView animateWithDuration:2
delay:0
options:UIViewAnimationOptionAllowUserInteraction
animations:^{[[self navTitle] setAlpha:0.9];}
completion:nil];
}
这个可以运行(顺便说一下:我想要它停止,这也是我将其连接到NSTimer的原因,这样我就可以取消它),唯一的问题是它从中灰色变成近白色,然后弹回来。有人知道如何从近白色重新动画到中灰色,以便我得到一个漂亮的平滑循环吗?
编辑_003:(解决方案)
戴夫·德隆(Dave DeLong)建议的代码(见下文),在修改为使用CALayer不透明度样式属性时确实有效:
UILabel *navTitle;
@property(nonatomic, retain) UILabel *navTitle;
.
// ADD ANIMATION
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"opacity"];
[anim setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
[anim setFromValue:[NSNumber numberWithFloat:0.5]];
[anim setToValue:[NSNumber numberWithFloat:1.0]];
[anim setAutoreverses:YES];
[anim setDuration:0.5];
[[[self navTitle] layer] addAnimation:anim forKey:@"flash"];
.
// REMOVE ANIMATION
[[[self navTitle] layer] removeAnimationForKey:@"flash"];