自定义UITable单元格如何构建具有唯一包含对象状态?

时间:2012-07-03 20:27:12

标签: iphone uitableview reuseidentifier

所以我有通过构建器定义的自定义表格单元格并通过nib加载(并且它具有其idexPath的属性)并且它有2个按钮。我想显示动态更改这些按钮状态的表。 IE第一个单​​元 - 启用,第二个单元 - 两个按钮都被禁用,第三个 - 第一个btn启用,第二个btn禁用,依此类推。
现在,如果我使用1个重用标识符,则所有单元格看起来都是我不想要的。我希望每个单元都有自己的视图,这意味着每个单元的唯一重用ID。
但是如何达到这个目标?如果我将在

创建一些独特的cellId
- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

这将是一个字符串,然后我无法创建对象含义相同的字符串。我可以使用相同的文本创建字符串,但这将是另一个对象,因此我无法通过reuseId再次使用此类cellId创建先前创建的单元格。所以我不能改变一个单元格的按钮状态,然后用

更新它
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:path] withRowAnimation:UITableViewRowAnimationNone];

但只有[tableView reloadData];才有效。

1 个答案:

答案 0 :(得分:1)

我有一种感觉,当您第一次使用 initWithStyle:reuseIdentifier:创建单元格时,您只设置单元格按钮的状态。这是错误的做事方式。您需要在每次调用 cellForRowAtIndexPath 时设置单元格的状态,无论它们是否被重复使用。在您的情况下,如果每个单元格具有相同的UI(两个按钮),那么它们应该共享一个reuseIdentifier。您的数据源应该负责维护单元格的状态, UITableViewCell对象。

这是区别:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     myCustomCell *cell = (myCustomCell *)[myTable dequeueReusableCellWithIdentifier:@"myCellIdentifier"];
     if (cell == nil) {
       // Load cell from nib here and set the cell's button states based on indexPath
     }
    return cell;
}

和此:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     myCustomCell *cell = (myCustomCell *)[myTable dequeueReusableCellWithIdentifier:@"myCellIdentifier"];
     if (cell == nil) {
       // Load cell from nib here
     }
    // set the cell's button states based on indexPath here
    return cell;
}