Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/107.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在Swift 3中设置背景色动画_Ios_Swift_Uiviewanimation - Fatal编程技术网

Ios 在Swift 3中设置背景色动画

Ios 在Swift 3中设置背景色动画,ios,swift,uiviewanimation,Ios,Swift,Uiviewanimation,我目前有一个静态背景颜色: self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0) 如何编写代码,在设定的秒数(例如每种颜色5秒)内创建一系列动画颜色,然后返回到颜色循环的开头 我试过以下方法 self.backgroundColor = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0) UIView.animate(withDuration:

我目前有一个静态背景颜色:

self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0)
如何编写代码,在设定的秒数(例如每种颜色5秒)内创建一系列动画颜色,然后返回到颜色循环的开头

我试过以下方法

self.backgroundColor = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
UIView.animate(withDuration: 5.0, animations: { () -> Void in
    self.backgroundColor = UIColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0);
    self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0)
})

…但这只是停留在最后一种蓝色上。

必须制作嵌套动画

    self.backgroundColor = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
    UIView.animate(withDuration: 5.0, animations: { () -> Void in
        self.backgroundColor = UIColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0);
    },
     completion: { finished in
        UIView.animate(withDuration: 5.0, animations: { () -> Void in
            self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0)
        }, completion: { finished in
            //other color do the same
        })

    })
您可以尝试以下方法:

    let maxNumberOfRepeats = 10
    var currentNumberOfRepeats = 0
    Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { timer in
        currentNumberOfRepeats = currentNumberOfRepeats + 1
        if currentNumberOfRepeats == maxNumberOfRepeats {
            timer.invalidate()
            UIView.animate(withDuration: 1, animations: { 
                self.backgroundColor = UIColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0) //return to first color
            })
        } else {
            UIView.animate(withDuration: 1, animations: {
                self.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0) //or any other random color
            })
        }
    }

确切地CoreAnimation在可设置动画的特性的当前值和动画块执行后确定的最终值之间插值。另外请注意,如果未使用块参数
finished
,则最好使用
completion:{in…}
。上面嵌套的动画中的代码将直接转到最后一种颜色(蓝色),并且在前几种颜色之间没有动画。