Monday, February 27, 2012

Using a Custom Prototype tableViewCell with an IOS Storyboard

I was having all sorts of issues (disappearing data, incorrect data showing up in table view cells) attempting to use a custom, prototype cell from a Storyboard in a sub-classed UITableViewController that pulls from Core Data. Using a technique found at StackOverflow and the following works:

1) Create a subclass of UITableViewCell, call it MyCustomTVCell

2) Create the custom xib (MyCustomTVCellXibFile) file, pull in a tableViewCell. Make it custom, and make sure to use a unique Reuse Identifier (My Unique Reuse ID).

3) In the Identity Inspector, assign it the MyCustomTVCell class

4) Pull in a label on the tableViewCell.

5) Control-drag from the label to the MyCustomTVCell.h file
to IBOutlets. (call it label01)

6) Use the method registerNib:forCellReuseIdentifier: in tableView:cellForRowAtIndexPath: (thanks @richard-venable)


static NSString *CellIdentifier = @"My Unique Reuse ID";

[tableView registerNib:[UINib nibWithNibName:@"MyCustomTVCellXibFile" bundle:nil] forCellReuseIdentifier:CellIdentifier];


7) Create a cell with the MyCustomTVCell subclass:

MyCustomTVCell *cell = (MyCustomTVCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
 

if (cell == nil) {
        cell = [[
MyCustomTVCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }


8) Assign CD data to the now extended properties of the cell, i.e.

cell.label01.text = "fetched data from CoreData";

It works.

1 comment:

Anonymous said...

Hi Vince, thanks for this tutorial! I found it very useful. I compiled a list of some top resources on creating custom tableviewcells with xcode storyboard- I included your post. Check it out, feel free to share. http://www.verious.com/board/Giancarlo-Leonio/creating-custom-table-view-cells-with-xcode-storyboard/