0

I am currently trying to load my custom table view cell from its own nib file instead of drawing the cell in code. It goes fine besides from the fact that I do not understand how I can make my table view contain more than one instance of my custom table cell. Let's see if I can explain my issue...

In my table view controller I have something like IBOutlet MyFancyCell *fancyCell; and then I make the controller the owner of MyFancyCell.xib and connects the outlet in the controller to the table cell view in Interface Builder. Having

[[NSBundle mainBundle] loadNibNamed:@"MyFancyCell" owner:self options:nil];

in my controller fancyCell ends up pointing to an instance of my fancy custom table view cell.

Now, what if I want two of those fancy cells in my table view?

Stine
  • 1,605
  • 5
  • 23
  • 44

1 Answers1

1

You just use that IBOutlet temporarily to load your custom cell. In your cellForRowAtIndexPathyou do something like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"MyFancyCell";

    MyFancyCell *cell = (MyFancyCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"MyFancyCell" owner:self options:nil];
        cell = fancyCell;
        self.fancyCell = nil;
    }

    // configure cell...

    return cell;
}
albertamg
  • 28,492
  • 6
  • 64
  • 71
  • I actually think that would work! =D I will try it out immediately! Thanks a lot!! – Stine May 02 '11 at 15:11
  • 1
    @stine You also might be interested in the checked answer to [this question](http://stackoverflow.com/questions/540345/how-do-you-load-custom-uitableviewcells-from-xib-files), which discusses two approaches to load custom cells from nib files that do not require to set the file's owner to your specific controller. These approaches let you reuse cells with different owners :) – albertamg May 02 '11 at 15:23
  • Thank you, I will try to read it without getting too confused :) – Stine May 02 '11 at 15:34