Reputation: 2214
On a view I got a label and a table view. The label gets updated every second through a timer which calls the function that updates the label's text. Now this works all fine. But as soon as a user swipes with his finger on the table view, the label's text stops updating.
Is there a way to prevent this behavior?
Upvotes: 2
Views: 484
Reputation: 1091
Your Label stops updating when you scroll tableview because both timer and tableView are on the same thread i.e main thread. You can try the below code
These two Methods are used to update the UILabel irrespective of tableView Scrolling
- (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];
}
});
}
These are the TableView datasource methods
- (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;
}
So, basically you need to keep the Lable updation portion under dispatch queue.
Hope this solution will help you. Happy Coding :)
Upvotes: 2