我有一个自定义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:
method中设置任何标签。加载自定义单元格的最佳方法应该是什么?我需要支持iOS 5+。第一种方法可能行不通,因为我想在initWithStyle:
方法中而不是在表格视图的方法中配置单元格的标签和样式?
谢谢!
您的代码中的错误cell.nameLabel.text
是仅在这种if (cell == nil) { ... }
情况下设置,而不是一般情况下设置。
加载自定义单元格的最简单方法是
registerNib:forCellReuseIdentifier:
如果电池在笔尖文件中定义,或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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句