有没有办法为 UIButton 的 textColor 属性设置动画?我找到了一些 UILabel 文本颜色动画的解决方案,但还没有看到 UIButton 的任何解决方案。
6 回答
使用带视图的过渡
[UIView transitionWithView:backButton
duration:0.5f
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
[backButton setTitleColor:[_peacock lighten:d.primary] forState:UIControlStateNormal];
}
completion:^(BOOL finished){
}];
NSTimer 作为动画工具绝对不是好东西,通常也不应该在需要精度(帧速率)的情况下用于计时。这篇博文完美地体现了我对如何处理不可动画 UILabel 属性的立场,这些属性应该通过 CA 而不是 NSTimer 发送到渲染服务器。您可以使用或包装 CATextLayer 并foregroundColor
在标准动画块中为其属性设置动画,而不是 UILabel。
这在这里得到了很好的回答。它基本上使用这个方便的家伙:
[UIView transitionWithView:duration:options:animations:^()completion:^()];
显然你需要使用
[UIButton setTitleColor:[UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0] forState:UIControlStateNormal];
至于实际上让它随着时间的推移动画和改变颜色,您需要创建一个 NSTimer 实例并使用 @selector 参数将其指向要运行的特定方法。每次计时器运行时,它都会触发该方法,然后更改 UIButton 的颜色。
[NSTimer scheduledTimerWithTimeInterval:2.0f
target:self
selector:@selector(updateCounter:)
userInfo:nil
repeats:YES];
另请查看: http ://servin.com/iphone/iPhone-Timers-and-Animated-Views.html
您可以使用两个放置在同一位置的不同颜色的按钮(或标签等):
button1 = UIButton(frame: frame)
button2 = UIButton(frame: frame) // same frame
button1.setTitleColor(UIColor.redColor(), forState: .Normal) // red
button2.setTitleColor(UIColor.blueColor(), forState: .Normal) // blue
之后,您可以通过 button2 的过渡动画达到颜色动画:
UIView.animateKeyframesWithDuration(
1.0, delay: 0, options: [.Autoreverse, .Repeat],
animations: {
UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.5, animations: {
self.button2.alpha = 1.0
})
UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.5, animations: {
self.button2.alpha = 0.0
})
}, completion: nil)
这不是真正的动画,但它会工作。
使用您想要为颜色设置动画的任何频率创建一个计时器。
让该计时器在changeColorOnButton
每次触发时调用一个方法。
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(changeColorOnButton:) userInfo:nil repeats:YES];
创建一个颜色数组,colorsArray
(或者提前安排颜色,或者将一堆颜色添加到数组中并将它们打乱以随机化。创建一个 int, intForColorInArray
.
在 changeColorOnButton 方法中,执行以下操作:
- (void) changeColorOnButton:(UIButton *) button {
UIColor *nextColor = [colorsArray objectAtIndex:intForColorArray];
[button.titleLabel.setTextColor:nextColor];
intForColorArray = (intForColorArray +1) % [colorsArray count];
}