【问题标题】:UILabel in UITableViewCell not updating on NSTimerUITableViewCell 中的 UILabel 未在 NSTimer 上更新
【发布时间】:2014-02-05 07:21:23
【问题描述】:

在 viewDidAppear 方法中,我初始化了一个 NSTimer。 (self.dayView 在 loadView 方法中初始化)。

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];


    self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(reloadTableView)
                                                userInfo:nil
                                                 repeats:YES];
}

- (void)reloadTableView {
    [self.dayView.tableView reloadData];
}

我的 cellForRowAtIndexPath 看起来像这样:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"cell for row at indexpath called");
    MatchEventCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier forIndexPath:indexPath];
    MatchEvent *event = [self getMatchEventAtIndexPath:indexPath];

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponents = [calendar components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit
                                                   fromDate:[NSDate date]
                                                     toDate:event.startDate
                                                    options:0];

    cell.textLabel.text = [NSString stringWithFormat:@"%d:%d:%d", [dateComponents hour], [dateComponents minute], [dateComponents second]];
    NSLog(@"TEXT = %@", cell.textLabel.text);

    return cell;
}

当我在模拟器中测试这个计时器时,我的单元格中的标签没有更新。 当我查看 NSLog 时,我看到“TEXT = ...”设置为 textLabel 的新值。

为什么我的标签没有在视觉上更新,虽然 NSLog 显示 textLabel 有一个新文本?

【问题讨论】:

    标签: objective-c uitableview nstimer


    【解决方案1】:

    每当您对底层数据源进行更改时,您都需要更新表视图手册。 UITableView's reloadData 方法是快速且低效的方法。 正确的做法是:

    NSArray *cells = [myTableView visibleCells];
    NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
    for (UITableViewCell *cell in cells) {
        [indexPaths addObject:[myTableView indexPathForCell:cell]];
    }
    [myTableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:NO];
    [indexPaths release];
    

    其余不可见的行将在您滚动并出现后更新。

    让我们知道这是否有效,否则可能是线程问题...

    【讨论】:

    • 对我不起作用..我已经尝试添加“performSelectorOnMainThread”-方法,但似乎仍然没有更新..奇怪的是 NSLog 告诉标签已更新,但没有视觉上的变化。
    • 正如我在您的代码中看到的,NSLog 不会打印与单元格文本标签相同的信息。会不会是个问题?
    • 不..我更改了这个示例以获得默认理解...我编辑了问题以使其正确!
    • 您尝试刷新的那些单元格是否可见?
    • 在重新加载数据后在您的重新加载表视图方法中尝试此操作,[self.tableView beginUpdates]; [self.tableView reloadRowsAtIndexPaths:@[indexPathOfYourCell] withRowAnimation:UITableViewRowAnimationNone]; [self.tableView endUpdates];
    猜你喜欢
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多