Dynamic Cell Height


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

How to work out the cell height of a piece of text in order to set the row height of a table dynamically.


Copy this code and paste it in your HTML
  1. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  2. {
  3. CGFloat result = 44.0f;
  4. NSString* text = nil;
  5. CGFloat width = 0;
  6. CGFloat tableViewWidth;
  7. CGRect bounds = [UIScreen mainScreen].bounds;
  8.  
  9. if (UIInterfaceOrientationIsPortrait(self.interfaceOrientation))
  10. tableViewWidth = bounds.size.width;
  11. else
  12. tableViewWidth = bounds.size.height;
  13.  
  14. width = tableViewWidth - 110; // fudge factor
  15. text = [self textForRow:indexPath.row];
  16.  
  17. if (text)
  18. {
  19. // The notes can be of any height
  20. // This needs to work for both portrait and landscape orientations.
  21. // Calls to the table view to get the current cell and the rect for the
  22. // current row are recursive and call back this method.
  23. CGSize textSize = { width, 20000.0f }; // width and height of text area
  24. CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:12.0f] constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];
  25.  
  26. size.height += 29.0f; // top and bottom margin
  27. result = MAX(size.height, 44.0f); // at least one row
  28. }
  29.  
  30. return result;
  31. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.