我已经通过以下步骤在我的 iPhone 应用程序中创建了一个自定义表格 View 单元格。
- 在我的 Storyboard中,我创建了一个示例单元格,将其拖入
UILabel
和UIImageView
。 - 添加了新文件,我将其创建为
UITableViewCell
的子类。 - 在 Interface Builder 中,我选择了我的单元格并将其类指定为我在第 2 步中刚刚创建的类。
- 在自定义表格 View 单元格的代码中,我创建了两个 IBOutlet 属性并将它们连接到 Storyboard中的
UILabel
和UIImageView
。 我的自定义表格 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/