[英]Swift 3 Timer in Timer
計時器中的計時器如何工作?
func startSequenz()
{
for mainCell in mainTable {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector:#selector(ViewController.run), userInfo: nil, repeats: true)
}
}
func run ()
{
for cell in table{
timer2 = Timer.scheduledTimer(timeInterval: 1, target: self, selector:#selector(ViewController.run2), userInfo: nil, repeats: true)
}
timer!.invalidate()
}
func run2()
{
currentSteps! += 1
print("\(currentSteps!)")
timer2!.invalidate()
}
執行func run2()
永遠不會停止。 我的目標是延遲執行run2和sleep(1)
凍結GUI。
更新:
我使用了Tom E答案,但部分有效。 但是GUI在執行結束時僅刷新一次。
func run ()
{
for cell in table{
DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(2)) {
// This code will be placed on a background queue and be executed a second later
// i do my stuff
DispatchQueue.main.async {
// Here you may update any GUI elements
self.currentCell = cell
self.currentStep! += 1
self.sectionHeaderText = "\(self.currentStep!) of \(self.totalSteps!)"
self.tableView.reloadSections(IndexSet(integer: 0), with: .none)
}
}
}
}
public override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0 : return sectionHeaderText
default : return nil
}
}
創建一個重復計時器似乎沒有多大意義,該計時器在第一次調用其action方法時將立即失效。
如果您尋求延遲代碼執行的正確方法,請查看Grand Central Dispatch。 這是具有非阻塞,延遲后台執行的代碼示例:
DispatchQueue.global().asyncAfter(deadline: .now() + .seconds(1)) {
// This code will be placed on a background queue and be executed a second later
DispatchQueue.main.async {
// Here you may update any GUI elements
}
}
請確保您沒有從后台隊列訪問任何GUI元素。 因此,該示例顯示了如何切換到主線程以進行任何GUI更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.