iOS 5中的自定义单元问题

AppsDev

我有一个自定义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:方法中而不是在表格视图的方法中配置单元格的标签和样式

谢谢!

马丁·R

您的代码中的错误cell.nameLabel.text是仅在这种if (cell == nil) { ... }情况下设置,而不是一般情况下设置

加载自定义单元格的最简单方法是

  • 使用registerNib:forCellReuseIdentifier:如果电池在笔尖文件中定义,或
  • registerClass:forCellReuseIdentifier:如果单元是通过编程方式创建的,则使用;或
  • 使用情节提要,并为表格视图将“ CustomCell”定义为“ Prototype Cell”。

例如(在中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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章