black
black

Reputation: 1263

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.

Upvotes: 0

Views: 2364

Answers (4)

Sahidul Islam
Sahidul Islam

Reputation: 139

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

Upvotes: 0

George
George

Reputation: 30451

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
}

Upvotes: 0

Vignesh J
Vignesh J

Reputation: 257

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
}

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100543

You can try:

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

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

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

}

Upvotes: 3

Related Questions