ios - 我的自定义 UITableViewCell 中的对象(使用 Storyboard创建)为零

标签 ios uitableview storyboard

我已经通过以下步骤在我的 iPhone 应用程序中创建了一个自定义表格 View 单元格。

  1. 在我的 Storyboard中,我创建了一个示例单元格,将其拖入 UILabelUIImageView
  2. 添加了新文件,我将其创建为 UITableViewCell 的子类。
  3. 在 Interface Builder 中,我选择了我的单元格并将其类指定为我在第 2 步中刚刚创建的类。
  4. 在自定义表格 View 单元格的代码中,我创建了两个 IBOutlet 属性并将它们连接到 Storyboard中的 UILabelUIImageView
  5. 我的自定义表格 View 单元格还包含一个方法,它接收另一个对象,从中设置自己的属性:

    -(void)populateWithItem:(PLEItem *)item
    {
        if (item.state == PLEPendingItem) {
            status.text = @"Pending upload..."; //status is a UILabel IBOutlet property
        }
        else if(item.state == PLEUploadingItem)
        {
            status.text = @"Uploading...";
        }
    
        imageView.image = [UIImage imageWithContentsOfFile:item.path]; //imageView is the UIImageView IBOutlet property
    }
    

此方法是从我的 tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 中调用的,如下所示:

    PLEPendingItemCell* cell = (PLEPendingItemCell*)[tableView dequeueReusableCellWithIdentifier:item_id];
    if (cell == nil) {
        cell = [[PLEPendingItemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:pending_id];
    }

    [cell populateWithItem:((PLEItem*)[itemList objectAtIndex:indexPath.row])];

    return cell;

问题是单元格总是显示为空。我在 populateWithItem 中设置了一个断点,并意识到状态 UILabel 和图像 UIImageView 在该方法中都是 nil。

IB 不应该初始化这些吗?如果没有,我应该在哪里做?

最佳答案

如果您在 Storyboard中设置您的单元格,您始终需要使用 tableView:dequeueReusableCellWithIdentifier:forIndexPath: 创建您的单元格,因为这是 Storyboard创建您的单元格并连接 View 的地方。

直接使用其构造函数创建一个单元格,就像在您的示例代码中一样,不会从 Storyboard、nib 等加载任何 subview 。您创建的类对 Storyboard原型(prototype)单元格一无所知。

关于ios - 我的自定义 UITableViewCell 中的对象(使用 Storyboard创建)为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14329334/

相关文章:

ios - 将 UnsafePointer<UInt8> 获取到 Int 以将编码的 Int 写入流

ios - 如何从 TableSource 修改 TableViewCell 内的 UIButton?

ios - Xcode 不会在 Storyboard中显示我的文本字段占位符文本

ios - 导航栏在 iPhone 4 (iOS 7.1.2) 中消失

ios - scrollViewDidScroll 快速调用多次

ios - 使用 GoogleVR 和 SceneKit 时纹理显示不正确

ios - 我想记住一个 (NSIndexPath *)indexPath 以便以后删除,但是崩溃了

ios - 状态栏文本颜色 iOS 7

ios - 使用 AFNetworking 解析 JSON

iOS (iPhone/iPad) SDK - UITableView 在 reloadData 上不刷新(numberOfSectionsInTableView 等不会在 reloadData 上被调用)