ios - 正在调用 cellForRowAtIndexPath : ever practical?

标签 ios uitableview

我见过很多 many 开发人员在实现 UITableViewDelegateUITableViewDataSource 时直接调用 cellForRowAtIndexPath: :

1) 检索单元格以获取它们存储在其中的模型元素 细胞:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MyCell *cell = (MyCell *)[tableView cellForRowAtIndexPath:indexPath];
    int secretCode = cell.secretCode;
    LaunchMissileViewController *vc = [[LaunchMissileViewController alloc] initWithSecretCode:secretCode];
    [self.navigationController pushViewController:vc];
}

2) 尝试设置单元格样式(这有明显的问题,但似乎很常见):

MyCell *cell = (MyCell *)[self cellForRowAtIndexPath:indexPath];
// or [tableView cellForRowAtIndexPat:indexPath];
cell.backgroundColor = [UIColor greenColor];

做出“只有框架应该永远调用cellForRowAtIndexPath:”的笼统声明是否安全?还是有一个实际的原因,人们可能会自己调用它?

最佳答案

我个人认为没有什么好的情况可以直接在数据源上直接调用 tableView:cellForRowAtIndexPath:

对于案例 #1,它只是糟糕的编码。单元格不应包含数据。数据源应该有数据,因此从实际数据源而不是单元格获取数据。

对于案例 #2,您只需要更新可见单元格。为此,您可以使用 UITableView cellForRowAtIndexPath: 方法。无需为单元格调用数据源。

我尽量不说“从不”,但真正需要通过调用数据源方法来获取单元格的情况应该是极其罕见的。

关于ios - 正在调用 cellForRowAtIndexPath : ever practical?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20510288/

相关文章:

ios - 从数组中的动态坐标对 Google 标记移动进行动画处理

iOs 注册来自相机胶卷的通知

ios - iPhone 横向模式问题

ios - Tableview header 标签在中心对齐

ios - 搜索栏处于事件状态时,快速 TableView 被锁定

ios - 如何在 xcode 中打开现有的本地 pod?

ios - firebase setValue 方法中缺少值阻止设置数据库中的其他值

iphone - 从 Nib 加载时,自定义单元永远不会排队?

swift - 如何在 TableView 中使用prepareForSegue 传递数据?

ios - UITableView.setEditing() 无法禁用编辑模式