2017-07-27 49 views
0

我正在使用計時器增加一個Int並按下按鈕我將當前數字記錄在一個數組中。我也有一個TableView來顯示數組的內容。一切工作正常,除了如果我抓住TableView,甚至有點滾動,定時器掛起,直到我釋放TableView。Swift 3.2 - 計時器()與TableView

無論我對TableView做什麼,該如何保持Timer運行?

這裏是我的ViewController.swift:

import UIKit 
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

    @IBOutlet var myTableView: UITableView! 

    var timer = Timer() 

    var isTimerOn = false 

    var counter = 0 

    var samples: [Int] = [] 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     myTableView.dataSource = self 
     myTableView.delegate = self 
    } 



    @IBAction func startStopButton(_ sender: Any) { 
     switch isTimerOn { 
     case true: 
      timer.invalidate() 
      isTimerOn = false 
     case false: 
      timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) {_ in 
       self.counter += 1 
       print(self.counter) 
      } 
      isTimerOn = true 
     } 

    } 

    @IBAction func recordButton(_ sender: Any) { 
     samples.insert(counter, at: 0) 
     myTableView.reloadData() 
    } 
} 
extension ViewController { 
    func numberOfSections(in tableView: UITableView) -> Int { 
     return 1 
    } 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return samples.count 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! MyCell 

     cell.number = samples[indexPath.row] 

     return cell 
    } 
} 

如果你需要它,你可以看到整個項目上: https://github.com/Fr3qu3ntFly3r/TimerTest

感謝您的幫助提前。

+0

檢查本網頁https://stackoverflow.com/questions/29204229/countdown-timer-on-uitableviewcell-scrolling-laggy-issue-of -uitableview – Rex

回答

0

發生這種情況的原因是使用scheduledTimer(timeInterval:invocation:repeats:)scheduledTimer(timeInterval:target:selector:userInfo:repeats:)類方法創建計時器並在默認模式下將其安排在當前運行循環中。

當我們滾動UIScrollview或UITableview時,主線程上的運行循環將切換到UITrackingRunLoopMode,並執行處於此模式的任務。 這就是爲什麼你在默認運行循環中的任務將是無論如何。

然後你釋放表視圖,運行循環切換到默認模式,計時器再次正常工作。

使用commonModes將您的計時器添加到RunLoop將解決此問題。

RunLoop.current.add(timer, forMode: .commonModes)

.commonModes)是常用的模式的可配置組。將輸入源與此模式關聯也會將其與組中的每個模式相關聯。

希望這可以幫助你:)

瞭解更多:

Run Loops Docs

+0

它工作完美。非常感謝! –

0

上就是錯的是

var timer = Timer() 

在這一點上,你正在創建一個完全沒用計時器對象。你應該做的是永遠不要有一個沒有實際計劃的定時器。所以:

var timer = Timer? 
// No variable isTimerOn 

然後在startStopButton:

if let timer = self.timer { 
    timer.invalidate() 
    self.timer = nil 
} else { 
    self.timer = Timer.scheduledTimer (...) 
} 
+0

感謝您的評論。修正了它:D –