你走在正确的道路上。由于您的自定义单元格正在其他地方使用,因此 xib 是加载它的好地方。至于实现,你可以做这样的事情。
假设您的表格视图是“静态的”并且有三个单元格,您可以在 viewDidLoad 中注册您的自定义笔尖:
- (void)viewDidLoad
{
[super viewDidLoad];
UINib *customCellNib = [UINib nibWithNibName:@"CustomCell" bundle:nil];
[self.tableView registerNib:customCellNib forCellReuseIdentifier:@"CustomIdentifier"]
}
然后在cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
if(indexPath.row == 0) {
cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier1"];
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1
reuseIdentifier:@"CellIdentifier1"];
}
}
/* Cell 2 ommited for brevity */
else if(indexPath.row == 2) {
//Just to demonstrate the tableview is returning the correct type of cell from the XIB
CustomCell *customCell = [tableView dequeueReusableCellWithIdentifier:@"CustomIdentifier"];
cell = customCell;
}
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
最后在 IB 中为 Xib 设置正确的Identifier 为单元格。
更新
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row == 0) {
cell.textLabel.text = [NSString stringWithFormat:@"Cell %d", indexPath.row];
}
else {
//custom cell here
//cell.textfield.text = @"blah blah";
}
}
配置单元格方法在某种程度上是用于主要使用NSFetchedResultsController(及其使用的delegate)放置的表格视图单元格的约定
这只是用适当的内容重置重复使用的单元格的一种便捷方法,并使cellForRowAtIndexPath: 更易于阅读。我什至制作了多个版本的 configureCell,例如 configureCustomCell1:atIndexPath,以进一步提高可读性。
希望这会有所帮助!