计时器中的计时器是如何工作的?
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) freez GUI的执行。
更新:
我用了汤姆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
}
}发布于 2017-05-05 09:07:50
创建一个重复计时器似乎没有多大意义,它将在第一次调用其操作方法时立即失效。
如果您想要找到适当的方法来延迟代码的执行,请看一下中央调度。下面是一个具有非阻塞、延迟后台执行的代码示例:
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更新。
https://stackoverflow.com/questions/43800532
复制相似问题