【问题标题】:Validity of the UITableView Cells in ViewWill AppearViewWillAppear 中 UITableView 单元格的有效性
【发布时间】:2014-09-09 05:59:39
【问题描述】:

我有什么
1)。容器有UITableView,它有两个自定义的UITableViewCells

2)。 Core Data 具有某些实体,该实体具有要显示的文本 UITableViewCell 每次我进入View

我在做什么?

1) 我选择了-viewWillAppear 方法,每次视图可见时都会调用该方法。

2) 在-viewWillAppear 中,我从核心数据中检索数据。

3) 从UITableView 检索到特定单元格

NSUInteger idxArr[] ={2,0};    // 2 nd section, 0th Row. 

NSIndexPath *cPath = [NSIndexPath indexPathWithIndexes:idxArr length:2];

myCell *tCell = (myCell *)[self.settings cellForRowAtIndexPath:cPath];
tCell.myLabel.text = rec.servername;  // rec.servername is from DC.

当我签入 lldb 时,

tCell was nil.


问题:
1)这是获得细胞的正确方法吗?

2) 或者,到-viewWillAppear 时,UITableView 还没有准备好?

我确定。

【问题讨论】:

  • 先尝试致电[self.settings reloadData]。好像你的 tableview 还没有准备好

标签: ios iphone objective-c uitableview ios5


【解决方案1】:

不应以编程方式调用方法-cellForRowAtIndexPath:。这是UITableView 的数据源方法,它包含一些单元重用优化。如果您在向下和向上滚动后更新视图,-tableView:cellForRowAtIndexPath 将再次被调用,您的更改将不可见。

如果你想更新特定的单元格,你应该更新:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YourCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellId" forIndexPath:indexPath];
    YourData *data = //Get your data here
    if (data.isReady) {
        cell.tf.text = data[indexPath.row].text; 
    } else {
        cell.tf.text = @"Not ready yet. Need to reload this cell later"; 
    }
    return cell;
}

当你完成获取数据时,然后调用下面的方法。

  [self.tableView reloadRowsAtIndexPaths:(NSArray *) withRowAnimation:UITableViewRowAnimationFade];

如果你想像@salaman140 所说的那样重新加载整个tableView(通常它并不慢),你可以调用[self.tableView reloadData] 来更新所有可见的单元格。

如果我是你,我不会使用:

NSUInteger idxArr[] ={2,0};    // 2 nd section, 0th Row. 
NSIndexPath *cPath = [NSIndexPath indexPathWithIndexes:idxArr length:2];

我会(更清楚):

NSIndexPath *cPath = [NSIndexPath indexPathForRow:0 inSection:2];

【讨论】:

    【解决方案2】:

    在为tableview调用reloadData之后,我们需要在从-cellForRowAtIndexPath:获取单元格之前调用-scrollToRowAtIndexPath:

    因为,当我们在第 2 部分调用一行时,它可能在我们滚动之前不在可见区域中。所以,cellForRowAtIndexPath: 返回 nil。

    【讨论】:

      【解决方案3】:

      您应该通过符合 tableView 数据源协议来填充单元格,然后在您的 viewWillAppear 中您应该在您的 tableView 上调用 reloadData。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多