swift how to switch background color when button is pressed

Viewed 516

hello I currently have an app that flashes a random color when the button is pressed but it gets stuck in a loop and I can't change to other colors when I press the button again. I would also like to have the message disappear when the button is pressed. thank you so much !!!

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/25, delay: 0.0, options:[UIView.AnimationOptions.repeat, UIView.AnimationOptions.autoreverse], animations: {
            self.view.backgroundColor = self.colors.randomElement()
            self.view.backgroundColor = .black
            self.view.backgroundColor = self.colors.randomElement()
        }, completion: nil)
        
        
    }


}

class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        UIView.animate(withDuration: 1/25, delay: 0.0, options:[UIView.AnimationOptions.repeat, UIView.AnimationOptions.autoreverse], animations: {
             self.view.backgroundColor = UIColor.black
             self.view.backgroundColor = UIColor.green
             self.view.backgroundColor = UIColor.darkGray
             self.view.backgroundColor = UIColor.red
             self.view.backgroundColor = UIColor.white        }, completion: nil)    }


}
1 Answers

Try this:

@IBAction func didTapButton() 
{
    self.view.backgroundColor = UIColor.clear   // <-- reset initial background outside animation block

    // then start the animation
    UIView.animate(withDuration: 1/25, delay: 0.0, options:[.autoreverse, .repeat, .allowUserInteraction], animations: { [weak self] in 
        self?.view.backgroundColor = self?.colors.randomElement()
    }, completion: nil)
}

i.e. just set the backgroundColor to a random color once in the animation block.

Use autoreverse to return the color to the original (clear or transparent in this example).

Use the repeat option to repeat the animation, forever.

Use the allowUserInteraction to allow user interaction during the animation.

"I would also like to have the message disappear when the button is pressed" ... not sure what this is referring to.

Related