ios - 按下按钮时如何快速切换背景颜色
问题描述
您好,我目前有一个应用程序在按下按钮时会闪烁随机颜色,但它会卡在一个循环中,当我再次按下按钮时,我无法更改为其他颜色。我还想让消息在按下按钮时消失。太感谢了 !!!
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) }
}
解决方案
试试这个:
@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
允许在动画期间进行用户交互。
“我还想让消息在按下按钮时消失”......不确定这是指什么。
推荐阅读
- python - 使用 Flask 将 HTML 登录代码与 apps.py Python 代码链接时出现问题
- r - 具有混合效应 Brain-Cousens 兴奋模型的 medrm(包 medrc)的 str2lang(x) 错误
- javascript - 如何按 2 列分组,但值在同一行
- python - 如何在 OpenCV python 中设置实时网络摄像头的阈值?
- python-3.x - python中二进制字符串中的参数替换
- javascript - NuxtJS 忽略特定文件或文件夹的 webpack/chokidar 观察者
- python - Visual Studio 代码上 Meraki python 库的 Unicode 错误
- python - 如何测试字符串是否包含存储在熊猫列表列中的子字符串之一?
- python - 方法在 if 语句之后在方法中间停止?
- r - 如何使用不一定经过每个点的 ggplot 将曲线拟合到我的数据中?