简体   繁体   中英

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?

sleep(3) seems to lock the view from updating its color. 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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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