问题
I've created a custom table view cell in my iPhone app through the following steps.
- 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 }
This method is called from my tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath as follows:
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;
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.
Shouldn't IB be initializing these? If not, where should I be doing that?
回答1:
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.
来源:https://stackoverflow.com/questions/14329334/objects-inside-my-custom-uitableviewcell-created-with-storyboard-are-nil