我正在开发一个非常基本的双 View 计时器应用程序,其中在 View1 上我有 30 个按钮(15 个按钮启动计时器,其中 15 个使每个相应的计时器无效),在 View2 上我有一些其他不相关的功能我的问题。
问题是我的用户在计时器仍在运行时在这两个 View 之间来回切换 - 在 View 之间切换时计时器仍会正常增加,但一旦来回切换它们就会停止更新各自的标签.
定时器是这样实现的:
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 不是很精通,并且有点不知所措——任何关于更好实现的帮助甚至想法都将不胜感激。谢谢!
最佳答案
您正在使用 segues 在 VC1 和 VC2 之间转换。当您从 VC2 返回时,您正在创建一个全新的 VC1,这就是您看不到标签更新的原因。
您应该使用unwind segue 从 VC2 返回到 VC1。参见 here了解如何设置和使用 unwind segue。
由于您使用滑动手势在 View 之间转换,因此您需要以编程方式调用unwind segue。见下半场this answer了解如何设置 unwind segue 并为其提供一个标识符,以便您可以从滑动处理函数中使用 performSegue(withIdentifier:sender:)
调用它。
关于ios - 在 View 之间切换后,Swift Timer() 不会更新标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42546130/