首页 文章

动画UIButton文本颜色

提问于
浏览
12

有没有办法动画UIButton的textColor属性?我已经为UILabel文本颜色动画找到了一些解决方案,但是UIButton没有看到任何解决方案 .

6 回答

  • 0

    NSTimer绝对不是一个好的动画工具,也不应该用于需要精度的一般计时(帧率) . 这个blog post完美地说明了我对如何处理非动画UILabel属性的立场,这些属性应该通过CA而不是NSTimer发送到渲染服务器 . 您可以使用或包装CATextLayer而不是UILabel,并在标准动画块中为其 foregroundColor 属性设置动画 .

  • 1

    使用视图转换

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

    回答非常好here . 它基本上使用这个方便的家伙:

    [UIView transitionWithView:duration:options:animations:^()completion:^()];
    
  • -2

    显然你需要使用

    [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

  • 15

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

    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)
    
  • 6

    这不是一个真正的动画,但它会起作用 .

    创建一个计时器,其频率与您想要的颜色一样 .

    每次启动时,该计时器都会调用一个方法 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];
    }
    

相关问题