我想定制一个简单的 UITableViewCell,这样我只运行一次定制并在以后添加值(例如,单元格标题)。我的应用程序的单元格更复杂——它有 subview 并使用自动布局;但是,我相信一个简单的示例将有助于集中精力实现目标。
我使用 iOS 8、Xcode 6.X、Objective-C 和 Nibs(没有 Storyboard)来保持简单。我没有为 UITableViewCell 创建自定义类。相反,我有以下代码:
- (void)viewDidLoad {
[super viewDidLoad];
//[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1; //FIXED VALUE FOR EXAMPLE'S SAKE
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 3; //FIXED VALUE FOR EXAMPLE'S SAKE
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"tableView:cellForRowAtIndexPath:");
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
NSLog(@"cell == nil");
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//CUSTOMIZING CELL THAT I WANT TO RUN ONLY ONCE
cell.backgroundColor = [UIColor redColor];
}
NSArray *numbersArray = @[@1,@2,@3];
cell.textLabel.text = [NSString stringWithFormat:@"%@", numbersArray[indexPath.row]];
return cell;
}
哪些输出:
tableView:cellForRowAtIndexPath:
cell == nil
tableView:cellForRowAtIndexPath:
cell == nil
tableView:cellForRowAtIndexPath:
cell == nil
第一个问题:为什么 cell == nil
运行了 3 次?运行自定义代码 cell.backgroundColor = [UIColor redColor];
3 次似乎很浪费。
现在,当我启用时:
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
并使用:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
代替:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
我得到输出:
tableView:cellForRowAtIndexPath:
tableView:cellForRowAtIndexPath:
tableView:cellForRowAtIndexPath:
第二个问题:为什么 cell == nil
根本不运行?
最后的问题:如何让 cell == nil
只运行一次,以便我只格式化 UITableViewCell 一次?有没有更好的方法来自定义一个简单的单元格,只运行一次自定义代码?
最佳答案
Why is cell == nil run 3 times? It seems wasteful to run the customization code cell.backgroundColor = [UIColor redColor]; 3 times.
表格 View 很可能一次显示三个单元格,因此需要三个不同的单元格对象。
Why isn't cell == nil run at all?
文档指出,如果您之前注册了标识符,-dequeueReusableCellWithIdentifier:forIndexPath:
总是会返回一个有效的单元格。它主要负责检查您是否需要一个新单元格。
How can I make cell == nil run only once so that I format the UITableViewCell only once?
你不知道。您将必须自定义每个实例。不过,我建议使用自定义子类,而不是从外部弄乱 UITableViewCell
。
关于ios - 有效地自定义一个简单的 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29333682/