好吧,所以你的问题是你正在调用 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()
功能。您首先创建一个新计时器并将其分配给timer
然后创建第二个计时器并将其分配给timer
同样,多余。另外,由于您没有在该方法之外保存计时器,因此无需创建变量(以保持相同的功能)。所以函数可以是:
func timerStarted(){
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true)
}
但您很有可能在某个时候想要取消此操作,因此我可能会将其存储为实例变量:
private var timer: NSTimer
func timerStarted(){
self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true)
}