使用Swift中的animateWithDuration更改标签颜色

4

我想要对一个标签的文本进行动画处理,如果值大于某个数,则将文本颜色更改为蓝色;如果值小于某个数,则将文本颜色更改为红色;否则保持原始的“黑色”颜色。

但是,UIView.animateWithDuration()会永久地将颜色更改为蓝色。我想要做的是,如果值大于或小于某个数,我希望将标签颜色更改为蓝色或红色,并在几秒钟后将其颜色返回到黑色。

这是我的代码:

@IBOutlet weak var label: UILabel!
let x = 10
let y = 20

if x > y 
{
UIView.animateWithDuration(2,animations:
            { () -> Void in self.label.textColor = UIColor.blueColor(); })
}

else if y < x
{
UIView.animateWithDuration(2,animations:
                    { () -> Void in self.label.textColor = UIColor.redColor(); })
}
else
{
 self.label.textColor = UIColor.blackColor()
}

我曾尝试使用以下方法调用Sleep函数,但没有成功。

self.label.textColor = UIColor.blueColor()
sleep(3)
self.label.textColor = UIColor.blackColor()
4个回答

8

UIView动画API无法对UILabel的textColor属性进行动画处理,需要使用CAAnimation。这里提供了一种使用CATransition实现的方法。

 func animate() {
    let x = 10
    let y = 20

    var finalColor: UIColor!

    if x > y {
        finalColor = UIColor.blueColor()
    } else {
        finalColor = UIColor.redColor()
    }

    let changeColor = CATransition()
    changeColor.type = kCATransitionFade
    changeColor.duration = 2.0

    CATransaction.begin()

    CATransaction.setCompletionBlock {
        self.label.textColor = UIColor.blackColor()
        self.label.layer.addAnimation(changeColor, forKey: nil)
    }
    self.label.textColor = finalColor
    self.label.layer.addAnimation(changeColor, forKey: nil)

    CATransaction.commit()
}

谢谢,这就是我想要的。 :) - Mohamed Horani

2

在Acluda的回答基础上,我建议将他的代码放在animateWithDuration:animations:completion变种方法的完成处理程序中。

UIView.animateWithDuration(2,
    animations: { () -> Void in self.label.textColor = UIColor.blueColor(); },
    completion: { (wentThrough: Bool) -> Void in
        { UIView.animateWithDuration(2,
              animations: { () -> Void in self.label.textColor = UIColor.blackColor(); }) })

你好,感谢你的回答,但是它会永久性地将颜色标签更改为蓝色,处理程序没有起作用。我还能做些什么来实现这个功能吗? - Mohamed Horani

1
UIView.transitionWithView(myLabel, duration: 0.25, options: .TransitionCrossDissolve, animations: {() -> Void in
            label.textColor = UIColor.redColor()
        }, completion: {(finished: Bool) -> Void in
        })

尝试一下 :)

我喜欢它!这是迄今为止我最喜欢的答案。 - Trev14
@Trev14 谢谢 :) - Nikita Khandelwal

0

没有逻辑告诉UIView在第一次动画完成后返回UIColor.blackColor。

考虑在蓝色/红色的动画调用之后添加这个功能。

UIView.animateWithDuration(2,animations:
        { () -> Void in self.label.textColor = UIColor.blackColor(); })

你的代码有问题。它和这个是一样的。label.textColor = UIColor.blueColor() label.textColor = UIColor.textColor()实际上,它将颜色从蓝色改为黑色,但用户不会注意到任何变化。 - Mohamed Horani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接