在iOS中每秒更新tableview中单元格中标签的文本
我希望通过计算两个在iOS中每秒更新tableview中单元格中标签的文本,ios,objective-c,uitableview,timer,nstimer,Ios,Objective C,Uitableview,Timer,Nstimer,我希望通过计算两个NSDate之间的时间,每秒更新tableView中每个单元格中每个标签的文本,就像:“~days~ hours~ minutes~ seconds” 在tableview中,它在cellforrowatinex处绘制单元格,它是tableViewController的代理 因此,我尝试在cellforrowatinex中使用计时器和方法reloadData:[self.tableview reloadData],但当时我认为它会产生无限循环并消亡 - (UITableView
NSDate
之间的时间,每秒更新tableView中每个单元格中每个标签的文本,就像:“~days~ hours~ minutes~ seconds”
在tableview中,它在cellforrowatinex
处绘制单元格,它是tableViewController
的代理
因此,我尝试在cellforrowatinex
中使用计时器和方法reloadData:[self.tableview reloadData]
,但当时我认为它会产生无限循环并消亡
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(updateLabel:)
userInfo:nil
repeats:YES ];
cell.timeLeftLabel.text=[self updateLabel:self.timer];
}
- (NSString *)updateLabel:(id)sender {
/*At this method , i calculate left days,hours,minutes,seconds between two nsdates
and I make the string by those values : */
NSLog(@"updateLabel : %@",timeLeftString);
return timeLeftString;
}
您需要每秒重新加载一个表,而不是一个标签或单元格—这意味着—创建一个计时器并调用方法[tableView reloadData]
- (void)viewDidLoad {
[super viewDidLoad];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(reloadTableViewData)
userInfo:nil
repeats:YES ];
}
- (void)reloadTableViewData
{
[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// setup cell
cell.timeLeftLabel.text=[self updateLabel:self.timer];
}
- (NSString *)updateLabel:(id)sender {
/*At this method , i calculate left days,hours,minutes,seconds between two nsdates
and I make the string by those values : */
NSLog(@"updateLabel : %@",timeLeftString);
return timeLeftString;
}
您不能在
cellforrowatinex
中使用[self.tableview reloadData]
正如你所说,它将创建一个无限循环
例如,在viewDidLoad
中创建一个计时器,如下例所示:
- (void)viewDidLoad
{
[super viewDidLoad];
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(increaseTimerCount) userInfo:nil repeats:YES]
}
- (void)increaseTimerCount
{
[self.tableView reloadData];
}
创建一个
NSTimer
,并将其设置为每秒一次:
[NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(targetMethod)
userInfo:nil
repeats:YES];
在targetMethod
中使用
[myTableView reloadData];
切勿从
cellforrowatinexpath:
调用任何reloadData
,insertRows…
,reloadrrows…
或'deleteRows…
方法(或修改表的任何其他方法)。顺便说一句,不需要reloadTableViewData
方法。设置计时器,目标为self.tableView
,并为reloadData
@rmaddy设置一个选择器。是的,很好,但如果您需要副作用和其他任何东西,最好将其包装在单独的方法中进行调试。