【发布时间】:2017-07-21 15:07:51
【问题描述】:
我正在开发一个非常基本的双视图计时器应用程序,其中在 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 不是很精通,有点不知所措——任何关于更好实现的帮助甚至想法都将不胜感激。谢谢!
【问题讨论】:
-
你是让viewwilldisappear上的计时器失效还是不需要
-
您是否使用 segues 在 2 个视图之间进行切换?如果是这样,您应该使用展开转场返回 VC1。
-
@vacawama 我正在使用 segues,是的——没听说过 unwind segue 现在绝对会调查它。
-
正常的 segue 每次都会创建一个新的目标 VC。因此,您通过在它们之间进行切换来创建越来越多的 VC。这就是为什么您的标签没有更新的原因,因为您正在寻找一个新的 VC1。
标签: ios objective-c swift timer nstimer