我需要使用swift每10秒执行一次函数。但我不知道如何继续。我知道我必须使用计时器,但没有找到有用的教程。
谢谢
答案 0 :(得分:3)
请阅读this。
override func viewDidLoad() {
super.viewDidLoad()
//Swift 3 selector syntax
var timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.update), userInfo: nil, repeats: true);
//Swift 2.2 selector syntax
var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: #selector(MyClass.update), userInfo: nil, repeats: true)
//Swift <2.2 selector syntax
var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)
}
// must be internal or public.
func update() {
// Something cool
}
答案 1 :(得分:1)
您可以使用NSTimer和RunLoop执行此操作:
func startTimer(){
let timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(yourFunction), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)
}
func yourFunction(){
//doStuff
}