[英]cellForRowAtIndexPath and Cell Configuration
好吧,所以使用UITableViewController的标准模板代码,我一直在使用cellForRowAtIndexPath:
根据数据源设置我的UITableViewCells。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//cell setup
cell.textLabel.text = @"Initial Data!";
return cell;
}
然而,作为一个有问题的做法,这突然让我感到震惊。 例如,假设我想这样做
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//some processing or data update is done here
//now I want to update the cell
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.textLabel.text = @"New Data";
}
看起来这是浪费的代码,因为检索单元格来更新它,导致它第二次从cellForRowAtIndexPath中的代码更新。
所以我应该把它的配置放在其他地方并以其他方式调用它,或者我应该以更聪明的方式在cellForRowAtIndexPath
中编写配置,以便对它进行简单的调用将更新UI
也许改变数据是一个更好的主意。
我假设你将从数组中获取数据? 然后更改didSelectRowAtIndexPath方法中的数据并重新加载所选单元格。
通常我会保留一个自我数组来将必要的数据应用到单元格。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//cell setup
MyObject *obj = ...; ///< retrieve obj from somewhere
cell.textLabel.text = obj.text;
return cell;
}
然后,选中后,我将修改我的数据源。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *newData = @"New Data"; ///<
// Update data source
MyObject *obj = ...;
obj.text = newData;
// Update UI
....
}
我更喜欢让MyObject处理有关数据处理的事情,例如,获取线程中单元格的缩略图,或计算复杂度结果。 控制器将结合数据和UI。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.