3

I've successfully been able to use registerNib to define a UITableViewCell's UI within an XIB that only has one UITableViewCell prototype within it.

In the interest of encapsulation, would it be possible to have an XIB with more than one UITableViewCell in it and still be able to load the proper cell using registerNib?

If so, how would one identify the desired cell prototype within the XIB in code?

I'm currently doing this in the tableView's VDL which works fine:

[self.tableView registerNib:[UINib nibWithNibName:@"LogoCell" bundle:[NSBundle mainBundle]]
     forCellReuseIdentifier:CellId];

Is there a way to specify which cell prototype within the XIB we want to use?

Thanks in advance.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Alex Zavatone
  • 4,106
  • 36
  • 54

2 Answers2

5
In the interest of encapsulation, would it be possible to have an XIB with more than one UITableViewCell in it and still be able to load the proper cell using registerNib?

No.

Eugene
  • 10,006
  • 4
  • 37
  • 55
1

Actually, it is possible. If you have some way of distinguishing the views in your XIB (tags, custom classes, etc), then you don't even need to register the nib – all you have to do is this:

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger cellIndex = 12345;
    NSString *cellIdentifier = @"MyAwesomeCell";

    // dequeue cell or, if it doesn't exist yet, create a new one from the nib
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell)
    {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"MyNibWithLotsOfCustomCells" owner:self options:nil];
        NSUInteger index = [topLevelObjects indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
            // if you distinguish the views by class
            return [obj isMemberOfClass:NSClassFromString(cellIdentifier)];
            // if you distinguish the views by tag
            return [(UIView*)obj tag] == cellIndex;
        }];
        cell = topLevelObjects[index];
    }

    // etc.
}

It's important to use dequeueReusableCellWithIdentifier: and not dequeueReusableVellWithIdentifier:forIndexPath: (the difference is explained in this thread).

Community
  • 1
  • 1
deltacrux
  • 1,186
  • 11
  • 18