我见过很多 many 开发人员在实现 UITableViewDelegate
和 UITableViewDataSource
时直接调用 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/