提问者:小点点

每次按下按钮时迅速使背景颜色闪烁或闪烁2种随机颜色


这款应用目前以黑屏开始,当按下中间的按钮时,它会在每次按下按钮时改变背景颜色。但我希望应用程序闪烁或闪烁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个答案

匿名用户

请在下面尝试

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")
    })
})

永远用在下面。

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`函数中处理它。