简体   繁体   中英

Empty prototype cell for a UITableView

I have a new project where I had to drag a prototype cell to a existing table view. I then

  • added some labels to the prototype cell with appropriate tags
  • set a identifier for the cell

and then in my tableview delegate when I get the delegate callback :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"myCustomCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
UILabel *nameLabel = (UILabel *)[cell viewWithTag:11];

I see that nameLabel is nil. I have double checked and tripled checked the tag and reusable identifier with no luck. In the storyboard, I see that the tableview has the pro type cell as its cell with the contentView showing my labels. What am I missing?

Do you ever create a new cell in the if (cell == nil) branch? If yes, you are creating a regular UITAbleViewCell there. Do not expect any custom lable there, because you don't load it from any nib file nor from the storyboard.

Of what type is the cell object? NSLog it or have a look in the debugger which type is actually created.

You are allocating UITableViewCell which don't contain your custom label. If you have created a View using Storyboard then you should allocate that view using following method.

You can create a Utility method to get Class instance from NibName

+ (id)loadNibNamed:(NSString *)nibName ofClass:(Class)objClass 
{
    if (nibName && objClass) 
    {
        NSArray *objects = [[NSBundle mainBundle] loadNibNamed:nibName 
                                                     owner:nil 
                                                   options:nil];            
        for (id currentObject in objects )
        {
            if ([currentObject isKindOfClass:objClass])
                return currentObject;
        }
    }
    return nil;
}

Use this in your code like

CustomViewCell *cell = (CustomViewCell *)[tableView dequeueReusableCellWithIdentifier:@"CustomViewCell"];
if (cell == nil)
{
    cell = [Utility loadNibNamed:@"CustomViewCell" ofClass:[CustomViewCell class]];
}

cell.yourLabel.text = @"Dummy Text";

Hopefully this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM