我怎样才能使背景色在每次按下按钮时连续闪现2个新颜色?现在它只显示两种颜色,但它们不会连续闪烁或闪烁。
import UIKit
class ViewController: UIViewController {
let colors: [UIColor] = [
.systemYellow,
.systemGreen,
.systemPurple,
.systemPink,
.systemRed,
.systemBlue,
.systemOrange,
.black,.gray
]
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .clear
}
@IBAction func didTapButton() {
UIView.animate(withDuration: 1/2, delay: 0, options: .curveEaseOut, animations: {
self.view.backgroundColor = self.colors.randomElement()
}, completion: { finished in
print("another animation! - 1")
UIView.animate(withDuration: 1/2, delay: 0, options: .curveEaseOut, animations: {
self.view.backgroundColor = self.colors.randomElement()
}, completion: { finished in
print("another animation! - 2")
})
})
}
}
像这样的?
可以使用[.repeat,.autoreverse]
选项重复和反转彩色动画。
然后,由于按钮是您正在动画的视图的子视图(在动画过程中,通常禁用视图及其子视图的用户交互),您可以添加.AllowUserInteraction
选项以允许再次按下按钮。
@IBAction func didTapButton() {
let color1 = self.colors.randomElement()
let color2 = self.colors.randomElement()
self.view.layer.removeAllAnimations()
self.view.backgroundColor = color1 /// set to color1
UIView.animate(withDuration: 1, delay: 0, options: [.repeat, .autoreverse, .allowUserInteraction]) {
self.view.backgroundColor = color2 /// now animate to color2, reverse, then repeat
}
}