在 View 上我有一个标签和一个表格 View 。标签通过计时器每秒更新一次,计时器调用更新标签文本的函数。现在一切正常。但是,一旦用户用手指在表格 View 上滑动,标签的文本就会停止更新。
有办法阻止这种行为吗?
最佳答案
当您滚动 tableview 时,您的标签将停止更新,因为计时器和 tableView 位于同一线程(即主线程)上。您可以尝试以下代码
这两个方法用于更新 UILabel,与 tableView 滚动无关
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrData = [NSMutableArray new];
for (int i = 0; i < 150; i ++) {
[arrData addObject:[NSString stringWithFormat:@"Row number %d",i]];
}
[self performCounterTask];
count = 10;
}
-(void)performCounterTask{
if (count == 0) {
count = 10;
}
double delayInSeconds = 1.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
// Your code here
if (count >= 0) {
[lblTimer setText:[NSString stringWithFormat:@"%ld",(long)count]];
count--;
[self performCounterTask];
}
});
}
这些是 TableView 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return arrData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = @"cell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.textLabel.text = [arrData objectAtIndex:indexPath.row];
return cell;
}
所以,基本上你需要将标签更新部分保留在调度队列下。
希望这个解决方案能够帮助您。快乐编码:)
关于uitableview - iOS : label stops updating when user scrolls through table view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24888480/