I'm migrating from customizing my TableViewCells in tableView:cellForRow:atIndexPath:
to using a custom UITableViewCell
subclass. Here's how I done it:
First, created empty XIB, dragged UITableViewCell
there and put a UILabel
on top. Created a class (subclass of UITableViewCell
) and in Interface Builder's properties editor set the class to MyCell
.
Then, in my TableViewController, put the following:
- (void)viewDidLoad
{
[super viewDidLoad];
// load custom cell
UINib *cellNIB = [UINib nibWithNibName:@"MyCell" bundle:nil];
if (cellNIB)
{
[self.tableView registerNib:cellNIB forCellReuseIdentifier:@"MyCell"];
} else NSLog(@"failed to load nib");
}
After that I wiped out all the custom code from tableView:cellForRow:atIndexPath:
and left only default lines:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"MyCell";
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
return cell;
}
When I ran this, I expected to see a bunch of cells with a single label in each cell (the very label that I dropped in the middle while creating XIB). But instead I see just plain white empty cells and adding/removing the components to the XIB layout doesn't help.
I spend A DAY trying different options like setting the reuseIdentifier in Interface Builder for custom cell XIB and loading the view in tableView:cellForRow:atIndexPath:
, but none helped.
...but it turned out, that the only thing that I missed, was clearing the reuseIdentifier for prototype cell in my Storyboard for this TableViewController. It seems that Storyboard initializes its views/components later that viewDidLoad
called, and instead of taking my nice custom cell, xCode sets the real cell view for reusing to just plain white cell which is the standard for newly created TableViewControllers.
So again: go to your TableView properties and remove the reuseIdentifier you set before ;)
I spend so much time for this, so I thought it might help someone if I share this experience here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With