2012-07-15 86 views
11

有没有办法让UIButton的textColor属性动画?我发现了一些UILabel文本颜色动画的解决方案,但对于UIButton没有看到。动画UIButton文本颜色

回答

6

的NSTimer是绝对没有好作为动画工具,也不应被用于报时一般在需要精密(帧速率)这blog post完美体现了我关于如何处理非动画UILabel属性的问题,应该通过CA发送给渲染服务器,而不是NSTimer。您可以使用或包装CATextLayer,并在标准动画块中为其foregroundColor属性设置动画效果,而不是UILabel。

+0

链接被破坏,这将是一个很好的例子... – user1506145 2013-11-02 09:37:10

+2

链接没有坏... – CodaFi 2013-11-02 17:51:05

0

很明显,你将需要使用

[UIButton setTitleColor:[UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0] forState:UIControlStateNormal]; 

至于真正得到它的动画和改变颜色随着时间的推移,你需要创建的NSTimer的实例,并使用@选择paramater把它指向一个特定的方法来运行。每次计时器运行时,它都会触发改变UIButton颜色的方法。

[NSTimer scheduledTimerWithTimeInterval:2.0f 
     target:self 
    selector:@selector(updateCounter:) 
    userInfo:nil 
    repeats:YES]; 

还检查了: http://servin.com/iphone/iPhone-Timers-and-Animated-Views.html

+0

同意。链接为+1 – bkbeachlabs 2012-07-15 03:52:11

+0

请注意,这不能取代良好的CA CA动画。 UIColor对象可能不是可动画的,但CGColor对象绝对是。如果您可以继承UILabel,那么您可以实现自己的文本渲染并使用固有的CA动画。 – CodaFi 2012-07-15 04:16:37

-2

这心不是一个真正的动画,但它的工作。

创建一个定时器,使其具有任何想要的动画频率。

有没有那个计时器在每次触发时调用一个方法,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]; 
} 
+0

从@Stuartsoft处理了计时器方法。信贷到期的信贷。 – bkbeachlabs 2012-07-15 03:51:24

1

这个回答非常好here。 它基本上使用这个方便的人: [UIView transitionWithView:duration:options:animations:^()completion:^()];

13

与视图使用过渡

[UIView transitionWithView:backButton 
          duration:0.5f 
          options:UIViewAnimationOptionTransitionCrossDissolve 
         animations:^{ 
          [backButton setTitleColor:[_peacock lighten:d.primary] forState:UIControlStateNormal]; 
         } 
         completion:^(BOOL finished){ 
         }]; 
+1

伟大的作品。此外,您可以使用父视图作为主要目标,然后在“动画”块中以所需的方式动画所有子视图 – Peterdk 2017-07-14 17:56:03

0

您可以使用两个按钮(或标签等),用不同的颜色,其放置在相同的位置:

button1 = UIButton(frame: frame) 
button2 = UIButton(frame: frame) // same frame 

button1.setTitleColor(UIColor.redColor(), forState: .Normal) // red 
button2.setTitleColor(UIColor.blueColor(), forState: .Normal) // blue 

之后,你可以达到的颜色动画通过按钮2的过渡动画:

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)