2016-10-31 25 views
4

私は時間に異なる瞬間に作成されUITableViewcellsを持っていると私はそれらの一つ一つが、オブジェクトがreloadData()複数のタイマ(スウィフト)

これが何であるかに追加されたときにトリガーする独立したタイマーを持っていると思います私は新しいセルを作成するたびconfigureLiveCellが呼び出されるときに問題が来るこれまで

import UIKit 

var timer = Timer() 
var blinkStatus:Bool! = false 
var time = 300 


class LiveViewCell: UITableViewCell { 

    let str = String(format:"%02d:%02d", (time/60), (time % 100)) 
    func processTimer() { 

     if time > 0 { 
      time -= 1 
      timeRemainingLbl.text = String(time) 
     } else if time == 0 { 
      timer.invalidate() 
      timeRemainingLbl.text = "Due!" 
      timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(LiveViewCell.blinkTimer), userInfo: nil, repeats: true) 

     } 

    } 

    func blinkTimer() { 
     if blinkStatus == false { 
      timeRemainingLbl.textColor = UIColor(red:1.00, green:0.00, blue:0.00, alpha:1.0) 
      blinkStatus = true 
     } else if blinkStatus == true { 
      timeRemainingLbl.textColor = UIColor.clear 
      blinkStatus = false 
     } 

    } 


    @IBOutlet weak var tableNumberLeftLabel: UILabel! 
    @IBOutlet weak var guestNumbersLabel: UILabel! 

    @IBOutlet weak var timeInTableLabel: UILabel! 
    @IBOutlet weak var tableNumberLbl: UILabel! 
    @IBOutlet weak var timeRemainingLbl: UILabel! 


    var table: Table! 


    func configureLiveCell(_ NT: Table) { 

     layer.cornerRadius = 20 
     timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(LiveViewCell.processTimer), userInfo: nil, repeats: true) 
     tableNumberLbl.text = "T" + String(NT.number) 
     timeRemainingLbl.text = String(time) 

    } 
} 

を行っています。タイマーはスピードアップしているようですが、私は各タイマーを独立させたいと思います。

答えて

3

prepareForReuseメソッドをオーバーライドします。

override func prepareForReuse() { 
    super.prepareForReuse() 

    timer.invalidate() 
} 

これは、別の行で使用するためにセルが返される直前に呼び出されます。ここでタイマーを無効にすると、configureLiveCellはまだ別のタイマーを作成しません。

BTW - また、deinitメソッドを追加し、そのタイマーも無効にする必要があります。

また、timerプロパティをオプションにして、無効化した後にnilに設定します。もちろん、オプションであることに対処するために適切なチェックを追加する必要があります。

最後に、timertime、およびblinkStatusをクラス内で移動することによってインスタンス変数に変更する必要があります。

+0

prepareForReuse()はどこに置く必要がありますか? – Christian

+0

あなたのセルクラスで。 – rmaddy

+0

これは動作しますが、別のView Controllerに行くたびに、すべてのセルが追加されてスピードアップします。私はこのLiveViewCellがすべてのviewControllersに表示されているとは言及していません – Christian

関連する問題