Storyboard - multiple UITableViewControllers with the same custom cell

I sometimes find myself copy/pastingin between user cells UITableViewsin my storyboard, which gradually becomes a maintenance nightmare (i.e. now you need to make simple changes to each user cell in a few UITableViews).

Is it possible to create one custom cell in the storyboard file or xib, and then refer to it from several UITableViews? I think it was necessary to specify a name NIBfor the cell static/prototype, similar to how you can specify a name NIBfor UIViewControllerwhen editing normal xib.

By the way ... I know how to do this with code. I am looking for a way to do this from the storyboard editor itself.

+5
source share
2 answers

I know a way, but it requires a little code in a custom class. Create a subclass of UITableViewCell that loads itself from the tip. Then just set the class of your cells to this subclass. For a good look-up method, replace it with a different version downloaded from nib, see this blog post .

+1
source

In fact, you do not need to create your own class. If you are coding version 4.0 or higher, you can use UINib to create it. You can also cache it for better performance.

UIViewController.h

@property (nonatomic, retain) UINib *cellNib;
@property (nonatomic, retain) IBOutlet MyCustomTableViewCell *customCell;

UIViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Cache the tableviewcell nib
    self.cellNib = [UINib nibWithNibName:@"MyCustomTableViewCell" bundle:nil];
}

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

    MyCustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        [self.cellNib instantiateWithOwner:self options:nil];
        cell = customCell;
        self.customCell = nil;
    }
    // Set title and such
}

Do not forget about its release in dealloc if you do not use ARC

0

All Articles