Loading a Reusable UITableViewCell from a Nib

IosIphoneUitableviewCocoa TouchInterface Builder

Ios Problem Overview


I am able to design custom UITableViewCells and load them just fine using the technique described in the thread found at http://forums.macrumors.com/showthread.php?t=545061. However, using that method no longer allows you to init the cell with a reuseIdentifier which means you have to create whole new instances of each cell at every call. Has anyone figured out a good way to still cache particular cell types for reuses, but still be able to design them in Interface Builder?

Ios Solutions


Solution 1 - Ios

Actually, since you are building the cell in Interface Builder, just set the reuse identifier there:

http://www.flickr.com/photos/63309029@N00/3453319855/" title="IB_reuse_identifier by lordbrutish, on Flickr">https://farm4.static.flickr.com/3537/3453319855_e275484e09.jpg" width="500" height="301" alt="IB_reuse_identifier" />

Or if you are running Xcode 4, check the Attributes inspector tab:

enter image description here

(Edit: After your XIB is generated by XCode, it contains an empty UIView, but we need a UITableViewCell; so you have to manually remove the UIView and insert a Table View Cell. Of course, IB will not show any UITableViewCell parameters for a UIView.)

Solution 2 - Ios

Just implement a method with the appropriate method signature:

- (NSString *) reuseIdentifier {
  return @"myIdentifier";
}

Solution 3 - Ios

Now, in iOS 5 there is an appropriate UITableView method for that:

- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier

Solution 4 - Ios

I can't remember where I found this code originally, but it's been working great for me so far.

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    static NSString *CellIdentifier = @"CustomTableCell";
    static NSString *CellNib = @"CustomTableCellView";
    
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
		NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CellNib owner:self options:nil];
		cell = (UITableViewCell *)[nib objectAtIndex:0];
    }
    
	// perform additional custom work...
	
    return cell;
}

Example Interface Builder setup...

alt text

Solution 5 - Ios

Look at the answer I gave to this question:

https://stackoverflow.com/questions/202471/is-it-possible-to-design-nscell-subclasses-in-interface-builder

It's not only possible to design a UITableViewCell in IB, it's desirable because otherwise all of the manual wiring and placement of multiple elements is very tedious. Performaance is fine as long as you are careful to make all elements opaque when possible. The reuseID is set in IB for the properties of the UITableViewCell, then you use the matching reuse ID in code when attempting to dequeue.

I also heard from some of the presenters at WWDC last year that you shouldn't make table view cells in IB, but it's a load of bunk.

Solution 6 - Ios

As of iOS circa 4.0, there are specific instructions in the iOS docs that make this work super-fast:

http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/TableViewCells/TableViewCells.html#//apple_ref/doc/uid/TP40007451-CH7

Scroll down to where it talks about subclassing UITableViewCell.

Solution 7 - Ios

Here is another option:

NSString * cellId = @"reuseCell";  
//...
NSArray * nibObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomTableCell" owner:nil options:nil];

for (id obj in nibObjects)
{
    if ([obj isKindOfClass:[CustomTableCell class]])
    {
        cell = obj;
        [cell setValue:cellId forKey:@"reuseIdentifier"];
        break;
    }
}

Solution 8 - Ios

Louis method worked for me. This is the code I use to create the UITableViewCell from the nib:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{	
	UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"CustomCellId"];
	
    if (cell == nil) 
    {
        UIViewController *c = [[UIViewController alloc] initWithNibName:@"CustomCell" bundle:nil];
        cell = (PostCell *)c.view;
        [c release];
	}

	return cell;
}

Solution 9 - Ios

I create my custom view cells in a similar manner - except I connect the cell through an IBOutlet.

The [nib objectAt...] approach is susceptible to changes to positions of items in the array.

The UIViewController approach is good - just tried it, and it works nice enough.

BUT...

In all cases the initWithStyle constructor is NOT called, so no default initialisation is done.

I have read various places about using initWithCoder or awakeFromNib, but no conclusive evidence that either of these is the right way.

Apart from explicitly calling some initialization method in the cellForRowAtIndexPath method I haven't found an answer to this yet.

Solution 10 - Ios

A while back I found a great blog post on this topic at blog.atebits.com, and have since started using Loren Brichter ABTableViewCell class to do all of my UITableViewCells.

You end up with a simple container UIView to put all of your widgets, and scrolling is lightning fast.

Hope this is useful.

Solution 11 - Ios

This technique also works and doesn't require a funky ivar in your view controller for memory management. Here, the custom table view cell lives in a xib named "CustomCell.xib".

 static NSData *sLoadedCustomCell = nil;

 cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
 if (cell == nil) 
 {
   if (sLoadedCustomCell == nil) 
   {		
      // Load the custom table cell xib
      // and extract a reference to the cell object returned
      // and cache it in a static to avoid reloading the nib again.

      for (id loadedObject in [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:nil options:nil]) 
      {
        if ([loadedObject isKindOfClass:[UITableViewCell class]]) 
        {
          sLoadedCustomCell = [[NSKeyedArchiver archivedDataWithRootObject: loadedObject] retain];
    	  break;
        }
    }
    cell = (UITableViewCell *)[NSKeyedUnarchiver unarchiveObjectWithData: sLoadedCustomCell];
  }

Solution 12 - Ios

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *simpleTableIdentifier = @"CustomCell";

CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}         

return cell;
}

Solution 13 - Ios

The gustavogb solution doesn't work for me, what I tried is :

ChainesController *c = [[ChainesController alloc] initWithNibName:@"ChainesController" bundle:nil];
[[NSBundle mainBundle] loadNibNamed:@"ChaineArticleCell" owner:c options:nil];
cell = [c.blogTableViewCell retain];
[c release];

It seems to work. The blogTableViewCell is the IBOutlet for the cell and ChainesController is the file's owner.

Solution 14 - Ios

From the UITableView docs regarding dequeueWithReuseIdentifier: "A string identifying the cell object to be reused. By default, a reusable cell’s identifier is its class name, but you can change it to any arbitrary value."

Overriding -reuseIdentifer yourself is risky. What happens if you have two subclasses of your cell subclass, and use both of these in a single table view? If they send the reuse identifier call onto super you'll dequeue a cell of the wrong type.............. I think you need to override the reuseIdentifier method, but have it return a supplanted identifier string. Or, if one has not been specified, have it return the class as a string.

Solution 15 - Ios

For what it's worth, I asked an iPhone engineer about this at one of the iPhone Tech Talks. His answer was, "Yes, it's possible to use IB to create cells. But don't. Please, don't."

Solution 16 - Ios

I followed Apple's instructions as linked by Ben Mosher (thanks!) but found that Apple omitted an important point. The object they design in IB is just a UITableViewCell, as is the variable they load from it. But if you actually set it up as a custom subclass of UITableViewCell, and write the code files for the subclass, you can write IBOutlet declarations and IBAction methods in the code and wire them up to your custom elements in IB. Then there is no need to use view tags to access these elements and you can create any kind of crazy cell you want. It's Cocoa Touch heaven.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGreg MartinView Question on Stackoverflow
Solution 1 - IosTim KeatingView Answer on Stackoverflow
Solution 2 - IosLouis GerbargView Answer on Stackoverflow
Solution 3 - IoswzsView Answer on Stackoverflow
Solution 4 - IosjrainbowView Answer on Stackoverflow
Solution 5 - IosKendall Helmstetter GelnerView Answer on Stackoverflow
Solution 6 - IosBen MosherView Answer on Stackoverflow
Solution 7 - IosJDLView Answer on Stackoverflow
Solution 8 - IosggarberView Answer on Stackoverflow
Solution 9 - IosswwView Answer on Stackoverflow
Solution 10 - IosericView Answer on Stackoverflow
Solution 11 - IosBill GarrisonView Answer on Stackoverflow
Solution 12 - IosMohitView Answer on Stackoverflow
Solution 13 - IosgroumpfView Answer on Stackoverflow
Solution 14 - IosSK9View Answer on Stackoverflow
Solution 15 - IosAugustView Answer on Stackoverflow
Solution 16 - IosDavid CasseresView Answer on Stackoverflow