自定义tableViewCell中的NSTimer

我从viewController激活我的自定义单元类中的function。 自定义单元类看起来像这样:

import UIKit class TableViewCell: UITableViewCell { var counter = 10 class func timerStarted(){ var timer = NSTimer() timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true) } class func update(){ let cell = TableViewCell() var count = cell.counter count = --count println(counter) } } 

问题是variables计数器不会改变,所以每隔一段时间打印一次。 我怎样才能使它每次都改变价值并倒计时呢?

任何build议,将不胜感激。

编辑:我正在使用一个长按手势识别器来触发该function,这是我不能使用didSelectRowAtIndexPath函数触发它的原因。 我的长按的代码如下所示:

 func longPressActive(gestureRecognizer:UIGestureRecognizer) { if (gestureRecognizer.state == UIGestureRecognizerState.Began) { var point = gestureRecognizer.locationInView(self.tv) if let indexPath = self.tv.indexPathForRowAtPoint(point) { TableViewCell.timerStarted() } } } 

好的,所以你的问题是你正在调用TableView类的类方法而不是实例函数。 你想获得一个实际的单元格实例的句柄,而不仅仅是类。 所以首先,你的TableCell类有适当的签名(即删除class前缀):

 class TableViewCell: UITableViewCell { var counter = 10 // No longer class functions! :) func timerStarted(){ var timer = NSTimer() timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true) } func update() { // Update counter counter-- // <-- performs the actual decrement for you println(counter) } } 

然后,只需更新您的长按即可激活实际单元格上的计时器,而不仅仅是单元格的类别:

 func longPressActive(gestureRecognizer:UIGestureRecognizer) { if (gestureRecognizer.state == UIGestureRecognizerState.Began) { var point = gestureRecognizer.locationInView(self.tv) if let indexPath = self.tv.indexPathForRowAtPoint(point) { // Check to make sure it is the correct subclass if let cell = self.tv.cellForRowAtIndexPath(indexPath: indexPath) as? TableViewCell { // Starting the timer on the actual cell, not just the cell class cell.timerStarted(); } } } } 

另外,我想对你的timerStarted()函数发表评论。 您首先创build一个新的定时器并将其分配给timer ,然后创build第二个定时器并将其分配给timer 。 另外,由于您没有将该计时器保存在该方法之外,因此不需要创buildvariables(以保持相同的function)。 所以这个function可能是:

 func timerStarted(){ NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true) } 

但有一个很好的机会,你会想在某个时候取消这个,所以我可能会把它作为一个实例variables存储:

 private var timer: NSTimer func timerStarted(){ self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true) } 
 override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) as TableViewCell cell.timerStarted() } 

对于你的tableview单元类:

 func timerStarted(){ var timer = NSTimer() timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true) } func update(){ counter = counter - 1 println(counter) }