[英]cellForRowAtIndexPath and Cell Configuration
Okay, so consumate with the standard template code for UITableViewController, I've been using cellForRowAtIndexPath:
to set up my UITableViewCells based on the data source. 好吧,所以使用UITableViewController的标准模板代码,我一直在使用
cellForRowAtIndexPath:
根据数据源设置我的UITableViewCells。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//cell setup
cell.textLabel.text = @"Initial Data!";
return cell;
}
However, this is suddenly striking me as a problematic practice. 然而,作为一个有问题的做法,这突然让我感到震惊。 For instance, lets say I want to do this
例如,假设我想这样做
- (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";
}
It seems like this is wasteful code, because retrieving the cell to update it, is causing it to be updated a second time from the code in cellForRowAtIndexPath. 看起来这是浪费的代码,因为检索单元格来更新它,导致它第二次从cellForRowAtIndexPath中的代码更新。
So should I be putting the configuration for the cell somewhere else and calling it some other way, or should I be writing the configuration in cellForRowAtIndexPath
in a more clever way so that a simple call to it will update the UI withou 所以我应该把它的配置放在其他地方并以其他方式调用它,或者我应该以更聪明的方式在
cellForRowAtIndexPath
中编写配置,以便对它进行简单的调用将更新UI
Maybe altering the data is a better idea. 也许改变数据是一个更好的主意。
I'm assuming you will get your data from an array? 我假设你将从数组中获取数据? Then alter the data in the didSelectRowAtIndexPath method and reload just the selected cell.
然后更改didSelectRowAtIndexPath方法中的数据并重新加载所选单元格。
Generally I keep a self array to apply necessary data to cell. 通常我会保留一个自我数组来将必要的数据应用到单元格。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//cell setup
MyObject *obj = ...; ///< retrieve obj from somewhere
cell.textLabel.text = obj.text;
return cell;
}
Then, when selected, I will modify my data source. 然后,选中后,我将修改我的数据源。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *newData = @"New Data"; ///<
// Update data source
MyObject *obj = ...;
obj.text = newData;
// Update UI
....
}
I prefer to make MyObject to handle things about data processing, for example, obtain a thumbnail for cell in a thread, or calculate complexity result. 我更喜欢让MyObject处理有关数据处理的事情,例如,获取线程中单元格的缩略图,或计算复杂度结果。 Controller will combine data and UI.
控制器将结合数据和UI。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.