如何使用Swift为标签的背景颜色设置动画

时间:2017-03-15 02:22:09

标签: ios animation swift3 uilabel uibackgroundcolor

我有这个代码完美地为背景颜色设置动画:

UIView.animate(withDuration: 2, delay: 0.0, options:[UIViewAnimationOptions.repeat, UIViewAnimationOptions.autoreverse], animations: {
        self.view.backgroundColor = UIColor(red: 0/255, green: 185/255, blue: 215/255, alpha: 1.0)
        self.view.backgroundColor = UIColor(red: 0/255, green: 78/255, blue: 215/255, alpha: 1.0)
        self.view.backgroundColor = UIColor(red: 0/255, green: 215/255, blue: 138/255, alpha: 1.0)
}, completion: nil)

但后来我尝试使用它来为标签的背景颜色设置动画,但是颜色较深,并且它不起作用:

UIView.animate(withDuration: 2, delay: 0.0, options:[UIViewAnimationOptions.repeat, UIViewAnimationOptions.autoreverse], animations: {
        self.topBar.backgroundColor = UIColor(red: 0/255, green: 159/255, blue: 184/255, alpha: 1.0)
        self.topBar.backgroundColor = UIColor(red: 0/255, green: 67/255, blue: 184/255, alpha: 1.0)
        self.topBar.backgroundColor = UIColor(red: 0/255, green: 184/255, blue: 117/255, alpha: 1.0)
}, completion: nil)

是否有错误,或者我可以做些什么来动画标签的背景颜色?

1 个答案:

答案 0 :(得分:2)

尝试动画layer.backgroundColor而不是backgroundColor

此代码适合我

    UIView.animate(withDuration: 2, delay: 0.0, options:[UIViewAnimationOptions.repeat, UIViewAnimationOptions.autoreverse], animations: {
        self.label.layer.backgroundColor = UIColor(red: 0/255, green: 185/255, blue: 215/255, alpha: 1.0).cgColor
        self.label.layer.backgroundColor = UIColor(red: 0/255, green: 78/255, blue: 215/255, alpha: 1.0).cgColor
        self.label.layer.backgroundColor = UIColor(red: 0/255, green: 215/255, blue: 138/255, alpha: 1.0).cgColor
    }, completion: nil)