调用cellForRowAtIndexPath:是否实用? [英] Is calling cellForRowAtIndexPath: ever practical?

查看:118
本文介绍了调用cellForRowAtIndexPath:是否实用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直接实现 UITableViewDelegate UITableViewDataSource 时,我见过很多许多开发人员将 cellForRowAtIndexPath:调用为:

I've seen many many developers when implementing a UITableViewDelegate and UITableViewDataSource directly call cellForRowAtIndexPath: to either:

1)检索单元格以获取存储在$ b内的模型元素$ b单元格:

1) Retrieve the cell to grab a model element that they stored within the cell:

-(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)尝试设置单元格样式(这有明显的问题,但似乎非常常见):

2) Attempt to style the cell (this has clear problems, but seems very common):

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

制作只有框架永远调用 cellForRowAtIndexPath:?或者是否有一个人可能自己称之为的实际原因?

Is it safe to make the blanket statement that "only the framework should ever call cellForRowAtIndexPath:"? Or is there a practical reason one might ever call it themselves?

推荐答案

就我个人而言,我认为没有好的案例可以直接在数据源上直接调用 tableView:cellForRowAtIndexPath:

Personally I don't think there are ever good cases to directly call tableView:cellForRowAtIndexPath: directly on the data source.

对于情况#1,它只是编码错误。单元格永远不应包含数据。数据源应具有数据,因此从实际数据源而不是单元格获取数据。

For case #1 it is simply bad coding. The cell should never contain the data. The data source should have the data so get the data from the actual data source, not the cell.

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

For case #2 you would only ever need to update a visible cell. And for this you can use the UITableView cellForRowAtIndexPath: method. No need to call the data source for the cell.

我尝试永远不要说从不但它应该是一个非常罕见的情况,你真的需要得到通过调用数据源方法来获取单元格。

I try never to say "never" but it should be an extremely rare case where you have a real need to get the cell by calling the data source method.

这篇关于调用cellForRowAtIndexPath:是否实用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆