Вызов метода по таймеру
Если код нужно выполнить через определенный интервал времени, поможет класс NSTimer и его статический метод scheduledTimerWithTimeInterval.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
/* Parameters:
1) interval — number of seconds between firings
2) target — object-owner of the called method
3) selector — name of the called method
4) userInfo — additional user info object (may be nil)
5) repeats — timer is fired once (false) or until invalidated (true)
*/
NSTimer.scheduledTimerWithTimeInterval(5,
target: self,
selector: "changeBackgroundColor:",
userInfo: nil,
repeats: true)
}
func changeBackgroundColor(timer: NSTimer) {
// Generate random color
let red = CGFloat(arc4random_uniform(3)) / 2
let green = CGFloat(arc4random_uniform(3)) / 2
let blue = CGFloat(arc4random_uniform(3)) / 2
let alpha = CGFloat(1)
let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
// Animate background color changes
UIView.animateWithDuration(1, animations: {
self.view.backgroundColor = color
})
print("New background color: \(color)")
// If the new color is white, then stop the timer
if color == UIColor(red: 1, green: 1, blue: 1, alpha: 1) {
timer.invalidate()
print("The timer is stopped")
}
}
}