Raesu
Raesu

Reputation: 310

Change style of UITableViewCell with Code

I have a TableViewController subclassed to use as my search results controller. I have no storyboard or xib for it so it is implemented entirely in code. I have only implemented the data source methods.

I am trying to make the cells of the style UITableViewCellStyleSubtitle but cannot get this to work. In viewDidLoad I use the code [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];, then in cellForRowAtIndexPath:, I have this:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
}

However, given my registerClass call I don't think cell is ever nil so the style is never being changed from the default. If I remove the registerClass call I get a crash with the following message: 'unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'. Removing the if block for cell has no effect.

This is such a small change I feel it shouldn't be necessary to subclass UITableViewCell or build it in Storyboard. Any help appreciated.

Upvotes: 0

Views: 2574

Answers (1)

Klevison
Klevison

Reputation: 3484

cell will be never nil if you call dequeueReusableCellWithIdentifier:forIndexPath:

Apple says: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/#//apple_ref/occ/instm/UITableView/dequeueReusableCellWithIdentifier:

dequeueReusableCellWithIdentifier:This method dequeues an existing cell if one is available or creates a new one using the class or nib file you previously registered. If no cell is available for reuse and you did not register a class or nib file, this method returns nil.

dequeueReusableCellWithIdentifier:forIndexPath: This method dequeues an existing cell if one is available or creates a new one based on the class or nib file you previously registered.

Try to do this:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
}

Upvotes: 5

Related Questions