首页 > 解决方案 > 按下按钮时如何快速切换背景颜色

问题描述

您好,我目前有一个应用程序在按下按钮时会闪烁随机颜色,但它会卡在一个循环中,当我再次按下按钮时,我无法更改为其他颜色。我还想让消息在按下按钮时消失。太感谢了 !!!

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


}

标签: iosswift

解决方案


试试这个:

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

即只需backgroundColor在动画块中将 设置为随机颜色一次。

用于autoreverse将颜色恢复为原始颜色(在此示例中为透明或透明)。

使用repeat选项重复动画,永远。

使用allowUserInteraction允许在动画期间进行用户交互。

我还想让消息在按下按钮时消失”......不确定这是指什么。


推荐阅读