Objects inside my custom UITableViewCell (created with storyboard) are nil

本小妞迷上赌 提交于 2020-01-14 14:25:29

问题


I've created a custom table view cell in my iPhone app through the following steps.

  1. In my storyboard, I created a sample cell, dragged in a UILabel and a UIImageView.
  2. Added new files, which I made a subclass of UITableViewCell.
  3. In Interface Builder, I selected my cell and I assigned its class as the class I just created in step 2.
  4. In the code for my custom table view cell, I created two IBOutlet properties and connected them to my UILabel and UIImageView in the storyboard.
  5. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!