我有一个非常基本的双视图计时器应用程序我在工作,其中在View1上我有30个按钮(15个按钮启动计时器,其中15个使每个相应的计时器无效)在View2上我有一些其他功能与我的问题无关。
问题是我的用户在定时器仍在运行时在这两个视图之间来回切换 - 定时器在视图之间切换时仍然会正常增加,但一旦切换来回停止更新各自的标签
定时器的实施方式如下:
switch timedBehavior {
case "Introduction":
timer1 = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
case "Observing Stationary":
timer2 = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action2), userInfo: nil, repeats: true)
case "Observing Moving":
timer3 = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action3), userInfo: nil, repeats: true)
default:
print("Error in Timer Button Func")
}
计时器无效按钮实现为:
switch stopButtons {
case "stpBtn1":
timer1.invalidate()
case "stpBtn2":
timer2.invalidate()
case "stpBtn3":
timer3.invalidate()
default:
print("Error in Stop Button Func")
}
每个计时器都执行此功能:(增加数字并更新标签)
func action()
{
totalTime1 += 1
timeLabel1.text = String(totalTime1)
}
到目前为止,我已尝试使其无效并立即重新启动特定计时器,如果它在viewDidLoad()
中运行 - 这实际上似乎创建了两个计时器,并使我的增量速度加倍。
我很遗憾不熟悉Swift并且有点亏本 - 任何有关更好实施的帮助或想法都会非常感激。谢谢!
答案 0 :(得分:1)
您正在使用segues在VC1和VC2之间进行转换。当您从VC2返回时,您正在创建一个全新的VC1,这就是您没有看到标签更新的原因。
您应该使用展开segue 从VC2返回VC1。有关如何设置和使用展开segue的信息,请参阅here。
由于您使用滑动手势在视图之间切换,因此您需要以编程方式调用展开segue 。请参阅this answer的后半部分,了解如何设置展开segue 并为其指定一个标识符,以便您可以从滑动处理程序函数中使用performSegue(withIdentifier:sender:)
调用它。