【发布时间】:2012-07-14 09:49:18
【问题描述】:
有没有办法为 UIButton 的 textColor 属性设置动画?我已经找到了一些 UILabel 文本颜色动画的解决方案,但还没有看到 UIButton 的任何解决方案。
【问题讨论】:
有没有办法为 UIButton 的 textColor 属性设置动画?我已经找到了一些 UILabel 文本颜色动画的解决方案,但还没有看到 UIButton 的任何解决方案。
【问题讨论】:
显然你需要使用
[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
【讨论】:
这不是真正的动画,但它会起作用。
创建一个计时器,使用您想要为颜色设置动画的任何频率。
让计时器在每次触发时调用一个方法,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];
}
【讨论】:
NSTimer 作为动画工具绝对不是好东西,通常也不应该在需要精度(帧速率)的情况下用于计时。这个blog post 完美地体现了我对如何处理不可动画的 UILabel 属性的立场,这些属性应该通过 CA 发送到渲染服务器,而不是 NSTimer。代替 UILabel,您可以使用或包装 CATextLayer 并在标准动画块中为其 foregroundColor 属性设置动画。
【讨论】:
这个回答很好here。 它基本上使用这个得心应手的家伙:
[UIView transitionWithView:duration:options:animations:^()completion:^()];
【讨论】:
在视图中使用过渡
[UIView transitionWithView:backButton
duration:0.5f
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
[backButton setTitleColor:[_peacock lighten:d.primary] forState:UIControlStateNormal];
}
completion:^(BOOL finished){
}];
【讨论】:
animations 块中按照您想要的方式为所有子视图设置动画
您可以使用两个不同颜色的按钮(或标签等)放置在同一位置:
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)
【讨论】: