每次按下按钮时,Swift 都会使背景颜色闪烁或闪烁 2 种随机颜色

时间:2021-04-16 21:34:53

标签: 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/12, delay:0, options:[ ], animations: {
            self.view.backgroundColor = self.colors.randomElement()
            self.view.backgroundColor = self.colors.randomElement()
        }, completion: nil)
    }
}

1 个答案:

答案 0 :(得分:0)

试试下面的

UIView.animate(withDuration: 1.0, delay: 0, options: .curveEaseOut, animations: {
    self.view.backgroundColor = self.colors.randomElement()
}, completion: { finished in
   print("another animation! - 1")
    UIView.animate(withDuration: 1.0, delay: 0, options: .curveEaseOut, animations: {
        self.view.backgroundColor = self.colors.randomElement()
    }, completion: { finished in
      print("another animation! - 2")
    })
})

编辑 1

在下面永久使用。

func showColor() {
    UIView.animate(withDuration: 1.0, delay: 0, options: .curveEaseOut, animations: {
        self.view.backgroundColor = self.colors.randomElement()
    }, completion: { finished in
       print("another animation! - 1")
       Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(showColorAgain), userInfo: nil, repeats: false)
    })
}

@objc func showColorAgain() {
    showColor()
}

现在要制作逻辑直到下一次单击,您可以在 zshowColorAgain` 函数中处理它。