timpone
timpone

Reputation: 19969

How to configure cellForRowAtIndexPath to handle two different custom UITableViewCell types

I am trying to use two different custom UITableViewCell's but am struggling with how to get this done. I have the following but think that everything needs to be called cell. Also, I'm not sure if my return type is correct. What is the canonical way to set this up?

This is a follow-up to this question (although not fully relevant).

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  static NSString *MenuHeaderCellIdentifier=@"HeaderCell";
  static NSString *MenuItemCellIdentifier=@"ItemCell";

  HeaderCell *cell = [self.menuTV dequeueReusableCellWithIdentifier:HeaderCellIdentifier];
  ItemCell *miCell = [self.menuTV dequeueReusableCellWithIdentifier:ItemCellIdentifier];
  
  id dic=self.tmpMenu.listItems[indexPath.row];
  if([dic isKindOfClass:[Header class]]){
    Header *menuHeader=(Header *)dic;
    cell.nameLabel.text=@"here";
    return cell;
  }else if([dic isKindOfClass:[Item class]]){
    Item *item=(Item *)dic;
    miCell.headerLabel.text=@"here";
    return miCell;
  }

Upvotes: 0

Views: 191

Answers (1)

Paulw11
Paulw11

Reputation: 114865

Assuming that you are using prototype cells in your Storyboard, or that you have otherwise registered your cell identifiers, then your code is almost right. You should only dequeue the type of cell you need -

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  static NSString *menuHeaderCellIdentifier=@"HeaderCell";
  static NSString *menuItemCellIdentifier=@"ItemCell";

  id dic=self.tmpMenu.listItems[indexPath.row];

  if([dic isKindOfClass:[Header class]]) {
    HeaderCell *headerCell = [self.menuTV dequeueReusableCellWithIdentifier:menuHeaderCellIdentifier];
    Header *menuHeader=(Header *)dic;
    headerCell.nameLabel.text=@"here";
    return headerCell;
  } else if([dic isKindOfClass:[Item class]]) {
    ItemCell *itemCell = [self.menuTV dequeueReusableCellWithIdentifier:menuItemCellIdentifier];
    Item *item=(Item *)dic;
    itemCell.headerLabel.text=@"here";
    return itemCell;
  }

Upvotes: 2

Related Questions