2017-03-02 48 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

相關問題