我的自定义 UITableViewCell(用故事板创建)中的对象为零 [英] Objects inside my custom UITableViewCell (created with storyboard) are nil
问题描述
我通过以下步骤在我的 iPhone 应用程序中创建了一个自定义表格视图单元格.
I've created a custom table view cell in my iPhone app through the following steps.
- 在我的故事板中,我创建了一个示例单元格,拖入一个
UILabel
和一个UIImageView
. - 添加了新文件,我将其创建为
UITableViewCell
的子类. - 在 Interface Builder 中,我选择了我的单元格,并将它的类指定为我刚刚在步骤 2 中创建的类.
- 在我的自定义表格视图单元格的代码中,我创建了两个 IBOutlet 属性并将它们连接到故事板中的
UILabel
和UIImageView
. 我的自定义表格视图单元格还包括一个方法,它接收另一个对象,从中设置自己的属性:
- In my storyboard, I created a sample cell, dragged in a
UILabel
and aUIImageView
. - Added new files, which I made a subclass of
UITableViewCell
. - In Interface Builder, I selected my cell and I assigned its class as the class I just created in step 2.
- In the code for my custom table view cell, I created two IBOutlet properties and connected them to my
UILabel
andUIImageView
in the storyboard. My custom table view cell also includes a method, where it receives another object from which it sets its own attributes:
-(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
都为零.
The problem is that the cells always show up empty. I set a breakpoint in populateWithItem and realized that both the status UILabel
and the image UIImageView
were nil inside that method.
IB 不应该初始化这些吗?如果没有,我应该在哪里做?
Shouldn't IB be initializing these? If not, where should I be doing that?
推荐答案
如果您要在故事板中设置单元格,则始终需要使用 tableView:dequeueReusableCellWithIdentifier:forIndexPath:
创建单元格因为那是故事板创建您的单元格并连接视图的地方.
If you're setting up your cell in the storyboard, you always need to create your cell using tableView:dequeueReusableCellWithIdentifier:forIndexPath:
because that's where the storyboard creates your cell and hooks up the views.
直接使用其构造函数创建单元格,就像在您的示例代码中一样,不会从故事板、笔尖等加载任何子视图.您创建的类对故事板原型单元格一无所知.
Creating a cell with its constructor directly, as in your sample code, won't load any subviews from a storyboard, nib, etc. The class you've made doesn't know anything about the storyboard prototype cells.
这篇关于我的自定义 UITableViewCell(用故事板创建)中的对象为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!