2017-03-02 60 views
0

我有一个非常基本的双视图计时器应用程序,我在View1上有30个按钮(15个按钮启动计时器,其中15个按钮分别使各自的无效定时器)和View2我有一些其他功能与我的问题不相关。Swift Timer()在切换视图之后不会更新标签

的问题是,我的用户来回切换这两种观点之间,而定时器仍在运行 - 视图之间切换时,计时器仍然会增加为正常的,但将停止更新他们各自的标签一旦被转回和向前。

的定时器实现为这样:

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() - 这实际上似乎创建了两个计时器,并加快了我的增量速度。

我不是非常好,斯威夫特精通不幸的是和我在一个小的损失的 - 更好的实现任何帮助,甚至想法将非常感激。谢谢!

+0

你是否使viewwilldisappear上的计时器无效或那不想要 – zombie

+1

您是否使用segues在2个视图之间进行切换?如果是这样,你应该使用unwind segue返回到VC1。 – vacawama

+0

@vacawama我正在使用segues,是的 - 没有听说过放松segue现在绝对会看到它。 – perratitus

回答

1

您正在使用segs在VC1和VC2之间转换。当你从VC2返回时,你正在创建一个全新的VC1,这就是为什么你看不到你的标签更新。

您应该使用一个展开segue从VC2返回到VC1。请参阅here了解如何设置和使用展开的细节。

由于您使用滑动手势在视图之间切换,因此您需要以编程方式调用展开segue。请参见this answer的下半部分,了解如何设置展开segue并为其指定一个标识符,以便您可以使用刷卡处理函数中的performSegue(withIdentifier:sender:)进行调用。

+0

正是我需要的++一些真棒引用 - 不能够感谢你! – perratitus

相关问题