如何让背景闪烁或连续闪烁,直到再次按下按钮,然后它会闪烁或闪烁 2 种新的随机颜色

时间:2021-04-16 23:27:26

标签: ios swift

如何让每次按下按钮时背景颜色连续闪烁两种新颜色?现在它只显示 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")
            })
        })
    }
}

1 个答案:

答案 0 :(得分:0)

类似的东西?

Screen starts black, but once button is tapped, screen transitions between random colors. After bring tapped again, screen transitions between 2 new random colors.

您可以使用 [.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
    }
}