load a reusable UITableViewCell from a XIB version 2

/ Published in: Objective C
Save to your folder(s)

Create a UITableViewCell subclass, add outlets for the controls you'll add later.
Create a View-based NIB
Delete the default 'view' in IB
Add a 'Table View Cell' instance
Set the 'Class Identity' to your UITableViewCell subclass.
Set the 'Identifier' (this is the reuse identifier) to be the name of your class - e.g. PersonDetailsInfoCell.
Add the controls you want in IB
Link the controls to the outlets in your subclass.

Then to actually load the custom cells add this odd piece of boilerplate code.. (here PersonDetailsInfoCell is my UITableViewCell subclass).

Copy this code and paste it in your HTML
  1. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  3. PersonDetailsInfoCell *cell = (PersonDetailsInfoCell *)[tableView dequeueReusableCellWithIdentifier:@"PersonDetailsInfoCell"];
  4. if ( cell == nil ) // i.e. there isn't a reusable one I can use.
  5. {
  7. // wierd boilerplate code for loading the cell from a NIB..
  8. NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"PersonDetailsInfoCell" owner:self options:nil];
  9. id firstObject = [topLevelObjects objectAtIndex:0];
  10. if ( [ firstObject isKindOfClass:[UITableViewCell class]] )
  11. cell = firstObject;
  12. else cell = [topLevelObjects objectAtIndex:1];
  13. }
  15. // set up properties...
  17. return cell;
  18. }
  20. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  21. return 68.0; // return the HEIGHT of your cell as you designed it in IB.
  22. }

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.