Reputation: 336
I occasionally find myself copy/pasting
custom cells between UITableViews
in my storyboard which is slowly becoming a maintenance nightmare (i.e., a simple change must now be made to each custom cell across several UITableViews
).
Is it possible to create one custom cell in a storyboard or xib
file and then reference it from multiple UITableViews
? I'm thinking there's got to be a way to specify a NIB
name for a static/prototype
cell similar to how you can specify a NIB
name for a UIViewController
when editing a normal xib
.
BTW... I know how to do this via code. What I'm looking for is a way to do this from within the storyboard editor itself.
Upvotes: 5
Views: 503
Reputation: 1612
Actually, you don't have to create a custom class. If you're coding for version 4.0 and up, you can use a UINib to create it. You can also cache it to improve 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
}
Don't forget about releasing it in dealloc if not using ARC
Upvotes: 0
Reputation: 10645
I know of a way, but it does require a little code in a custom class. Make a subclass of UITableViewCell that loads itself from a nib. Then just set the class of your cells to this subclass. For a good method of having a view replace itself with a different version loaded from a nib see this blog post.
Upvotes: 1