【问题标题】:iOS: label stops updating when user scrolls through table viewiOS:当用户滚动表格视图时标签停止更新
【发布时间】:2014-07-22 13:17:16
【问题描述】:

在一个视图中,我得到了一个标签和一个表格视图。标签通过一个计时器每秒更新一次,该计时器调用更新标签文本的函数。现在这一切正常。但是一旦用户用手指在表格视图上滑动,标签的文本就会停止更新。

有没有办法防止这种行为?

【问题讨论】:

    标签: uitableview ios7 xcode5


    【解决方案1】:

    当您滚动 tableview 时,您的 Label 会停止更新,因为 timer 和 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;
    
    }
    

    所以,基本上你需要将 Lable 更新部分保留在调度队列中。

    希望此解决方案对您有所帮助。快乐编码:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多