我有一个自定义 UITableViewCell
子类,我读到这应该是为 iOS 5 加载自定义单元格的正确方法:
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = [tv dequeueReusableCellWithIdentifier:@"customCell"];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"customCell"];
// Configure cell
cell.nameLabel.text = self.customClass.name;
}
return cell;
}
但是当我运行应用程序时,标签文本没有显示。但是,我也尝试过这种方式:
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:@"customCell"];
if (cell == nil) {
NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:nil options:nil];
for (UIView *view in views) {
if([view isKindOfClass:[UITableViewCell class]])
{
cell = (CustomCell *)view;
}
}
// Configure cell
((CustomCell *)cell).nameLabel.text = self.customClass.name;
}
return cell;
}
这样标签就会显示出来,但是任何
reuseIdentifier
设置在 loadNibName:
方法。加载自定义单元格的最佳方式应该是什么?我需要支持 iOS 5+。第一种方法是否行不通,因为我要在 initWithStyle:
中配置单元格的标签和样式?方法而不是表格 View 的方法?谢谢!
最佳答案
您的代码中的错误是 cell.nameLabel.text
仅在 if (cell == nil) { ... }
中设置情况而不是一般情况。
加载自定义单元格的最简单方法是
registerNib:forCellReuseIdentifier:
如果单元格在 nib 文件中定义,或 registerClass:forCellReuseIdentifier:
如果单元格是以编程方式创建的,或者 例如(在
viewDidLoad
中):[self.tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:@"customCell"];
然后
dequeueReusableCellWithIdentifier
将始终返回一个单元格,因此 cellForRowAtIndexPath
简化为- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = [tv dequeueReusableCellWithIdentifier:@"customCell"];
cell.nameLabel.text = self.customClass.name;
return cell;
}
关于ios - iOS 5 中的自定义单元格问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18227023/