我必须创建类似的东西,有一个 UITableView,它有很多行和多个部分,每一行都有不同的计时器,以 'hh:mm:ss' 格式显示,它每秒递减一次,就像倒计时一样。
我遇到的问题是,当我滚动 UITableView 时,很少有 UILabel 重新初始化并且倒计时时间消失,甚至它会被几个单元格覆盖。 我正在使用以下代码来实现我的要求:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//Somewhere, in this method
elapsedTimeTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(runningTimer:) userInfo:dic repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:elapsedTimeTimer
forMode:NSRunLoopCommonModes];
}
-(void)runningTimer:(NSTimer *)timer {
secondsLeft --; //I'm able to get seconds
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
cell.lblTime.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
请帮我解决这个问题。任何形式的帮助,一定会感激。
谢谢.!!..
最佳答案
您需要有一个元素数组或字典来跟踪您的计时器。
uitableview 中的每个单元格都会被重用,因为您的计时器会受到影响。
代替 elapsedTimeTimer
我会用
elapsedTimeTimers[indexPath.row]
其中 elapsedTimeTimers
是计时器数组。
当然,这适用于只有一个部分的情况。如果你有更多,那么你将不得不计算正确的索引。此外,如果您有一个对象来保存所有这些数据,您可以使用对象 ID 或类似的东西。
关于ios - NSTimer 不适用于 UITableviewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28092115/