简体   繁体   English

iOS 延迟更改背景颜色 (swift)

[英]iOS changing background color with delay (swift)

I want to set the view's background color and change it to another color after a certain delay.我想设置视图的背景颜色并在一定延迟后将其更改为另一种颜色。 Here is how I tried it:这是我尝试的方法:

print("setting color 1")
self.view.backgroundColor = UIColor( rgb: 0xFF0000)
print("sleeping")
sleep(3)
self.view.backgroundColor = UIColor( rgb: 0xFFFF00)
print("setting color 2")

However, I don't get the first color.但是,我没有得到第一种颜色。 The app stays at its initial color, waits for 3 seconds and changes than to color 2. No sign of color 1. How to fix that?应用程序保持其初始颜色,等待 3 秒,然后更改为颜色 2。没有颜色迹象 1。如何解决这个问题?

sleep(3) seems to lock the view from updating its color. sleep(3)似乎锁定视图更新其颜色。 However, if I call myButton.isEnabled = false and set it after the delay back to true , the button behaves as expected and stays disable during the delay.但是,如果我调用myButton.isEnabled = false并在延迟后将其设置回true ,则按钮会按预期运行并在延迟期间保持禁用状态。

You can try: 你可以试试:

self.view.backgroundColor = UIColor( rgb: 0xFF0000)

DispatchQueue.main.asyncAfter(deadline: .now()+3.0 ) {

  self.view.backgroundColor = UIColor( rgb: 0xFFFF00)

}

Your problem solved by using Timer. 使用计时器解决了您的问题。 just paste the code inside viewDidLoad function. 只需将代码粘贴到viewDidLoad函数中即可。

Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(change), userInfo: nil, repeats: false)

Following function inside your class 班级内的跟随功能

@objc func change() {
  view.backgroundColor = .black  //change your color
}

Create this function (can be used whenever you want): 创建此函数(可随时使用):

// MARK: Create delay
func delay(_ delay: Double, closure: @escaping ()->()) {
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}

Then to create the effect you want, do: 然后,创建所需的效果,请执行以下操作:

self.view.backgroundColor = UIColor( rgb: 0xFF0000) // Display red

delay(3) {
    self.view.backgroundColor = UIColor( rgb: 0xFFFF00) // Display yellow
}

Try this for swift 5试试这个 swift 5

self.view.backgroundColor = UIColor( rgb: 0xFF0000)
DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in
    self?.view.backgroundColor = UIColor( rgb: 0xFFFF00)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM