ios - iOS 5 中的自定义单元格问题

标签 ios uitableview custom-controls

我有一个自定义 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:如果单元格是以编程方式创建的,或者
  • 使用 Storyboard 并将“CustomCell”定义为表格 View 的“原型(prototype)单元”。

  • 例如(在 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/

    相关文章:

    ios - 在横向应用程序中打开 iAds 会破坏整个方向

    ios - 如何让 uitableview 一次加载多个部分?

    ios - 轻按时更改UIButton的图像

    uinavigationcontroller - xcode4.2 (storyboard, Navigation Controller) 如何为 UINavigationBar 设置自定义图像

    c# - 直接在 Visual Studio 项目中使用自定义控件

    ios - View Controller 中的两个 TableView : Swift

    ios - 如何在 Swift 的另一个类中设置变量值

    iphone - 当系统改变屏幕亮度时,iOS 会发送通知吗?

    ios - 快速点击(选择)最后一个选项时取消选择所选选项

    user-interface - 在 BlackBerry 中创建自定义布局