ios - NSTimer 不适用于 UITableviewCell

标签 ios uitableview nstimer reload countdown

我必须创建类似的东西,有一个 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/

相关文章:

ios - 将标签栏与 MVVM Light (iOS) 结合使用

ios - iOS 6.1 需要代码签名

objective-c - NSTimer 是否可以在指定时间之前触发?

iphone - 使用 NSTimer 的序列动画

swift - 使用 #selector swift3 时出现 NSInvalidArgument 异常

objective-c - 如何从在线目录加载 UIImage 数组中的图像并将其存储在应用程序中

ios - 在iOS中唯一标识设备

ios - 应用程序试图在目标上推送一个 nil View Controller

Swift:表格 View 中的动态单元格

ios - 使用自定义 UITableViewCells 循环遍历 UITableView