I am converting over to iOS 5 and storyboards. When I have a table view with default cell style, everything works fine.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifierFromStoryboard"]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyIdentifierFromStoryboard"]; } return cell; }
I have seen examples where the "if (cell == nil)" block is removed. However if I take it out, my app crashes with the message: "UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:". This is not a problem because it works as shown above.
My problem is that I want to use a custom style for the cell and thus cannot use initWithStyle. How do I initialize a custom cell that I have designed on the storyboard?
The old pre-5 app had a nib and class that used something like this, but now I'm using the storyboard.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { MyCustomTableCell *cell = (MyCustomTableCell *) [tableView dequeueReusableCellWithIdentifier:@"MyCustomIdentifier"]; if (cell == nil) { NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyCustomTableCell" owner:self options:nil]; cell = (MyCustomTableCell *) [nib objectAtIndex:0]; } return cell; }
First, design your table cell on Storyboard whatever you want. Now, make a subclass of UITableViewCell and assign this class to your prototype custom cell which you have designed on Storyboard. Also, don't forget to set "reuse identifier in Storyboard table cell.
A prototype cell acts a template for your cell's appearance. It includes the views you want to display and their arrangement within the content area of the cell. At runtime, the table's data source object creates actual cells from the prototypes and configures them with your app's data.
The same way that you create a UIViewController or UITableViewController : In your project, go to New File. Select Cocoa Touch Class under iOS. The subclass is UITableViewCell and the name is whatever name you're giving it. Within that class, you drag your buttons, labels, etc to create your outlets.
This way
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } return cell; }
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