除非点击单元格,否则UITableViewCell字幕不会更改

时间:2014-08-15 21:24:43

标签: ios objective-c uitableview

我表格中的单元格有一个字幕集,可以显示从Web服务器加载的一些额外信息。当应用加载字幕时,只需说“#34;正在加载..."然后当收到响应并解析时,单元格会更新。

问题是,除非我点击单元格,否则字幕将保留在"正在加载..."。一旦我点击它就会更新到正确的字幕。

这里我初始化单元格,并在执行http请求时设置临时字幕<​​/ p>

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    // Setting the tableviewcell titles
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    cell.detailTextLabel.text = @"Loading...";
    cell.detailTextLabel.enabled = NO;

    return cell;
}

我尝试过在不同的地方调用请求方法: willDisplayCellcellForRowAtIndexPath

从Web服务器获取数据的方法使用异步NSURLConnection,当收到成功的响应时,我使用以下命令更新单元格字幕文本:

// Map Reduce the array used by the TableView
for (int i = 0; i < [self.routes count]; i++) {
if(cellMatches){
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
    cell.detailTextLabel.text = @"Data received!";
    cell.userInteractionEnabled = YES;
    cell.textLabel.enabled = YES;
    cell.detailTextLabel.enabled = YES;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

我知道您可以使用tableView reloadRowsAtIndexPaths重新加载特定的单元格,但在实现此代码时似乎无法正常工作:

[self.tableView beginUpdates];
// Change cell subtitle
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];

我有一个定时器设置为每隔30秒调用一次请求方法,当调用它时它没有问题,并且立即更新字幕而不必点击它。所以我认为问题是该单元格没有初始化,或者可能是在发出Web请求后重新初始化。但在此方法中我不会致电reloadAllData

3 个答案:

答案 0 :(得分:0)

试试这个:

[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];

而不是:

[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];

答案 1 :(得分:0)

您需要做的是更新cellForRowAtIndexPath,以便检查数据。如果数据可用,请将字幕设置为数据,否则显示&#34;正在加载&#34;。这要求您拥有某种数据模型,以便在收到数据时存储数据。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    BOOL enabled = YES;
    NSString *subtitle = ... // get the value from the data model
    if (subtitle) {
        cell.textLabel.text = ... // whatever value goes here
        cell.detailTextLabel.text = subtitle;
        cell.detailTextLabel.enabled = YES;
    } else {
        // There's no value for this row yet - show "Loading"
        cell.textLabel.text = ... // whatever value goes here when loading
        cell.detailTextLabel.text = @"Loading";
        cell.detailTextLabel.enabled = NO;
    }

    return cell;
}

请确保根据需要在if/else语句的两半中设置相同的单元格属性集。

获取新数据并更新数据模型后,只需调用reloadRowsAtIndexPaths:以获取正确的单元格路径即可。然后,上面的代码将正确更新单元格。

现在应该删除您更新单元格的代码,因为它不是正确的方法。

答案 2 :(得分:0)

除了rmaddy的解决方案,我还需要添加一个重要的事情found in a similar question

dispatch_async(dispatch_get_main_queue(), ^{
    [self.tableView reloadData];
});

完全解决了这个问题。

相关问题