1

does anybody know how to set up a cell in a TableView with a variable height depending on the content of a label?

on the network and 'full of tutorials but for ios7 of 5 Xcode is deprecated and all the information I have very clear ... can you help?

kAiN
  • 2,559
  • 1
  • 26
  • 54

1 Answers1

2

You override tableView:heightForRowAtIndexPath: and in there calculate the height of the content based on the size it will be when rendered in your chosen font:

So, something like this:

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
   NSString *content = [self.contentArray objectAtIndex:indexPath.row];

   // Max size you will permit
   CGSize maxSize = CGSizeMake(200, 1000);
   CGSize size = [content sizeWithFont:font constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];
   return size.height + 2*margin;
}

I found I needed to add some padding, hence the 'margin' variable above. Note that the code above constrains the text to a width of 200px, which you may not want.

smee
  • 361
  • 3
  • 4
  • sizeWithFont:font constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping]; Deprecated in ios7 ... This is the my problem :( – kAiN Sep 28 '13 at 23:48
  • Any ideas for this problem? – kAiN Sep 29 '13 at 13:48
  • 1
    A completely comprehensive answer to this has been posted in [this answer](http://stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights). I recommend using that approach because it's a complete solution for custom table view cells. See also the [sample project](https://github.com/smileyborg/TableViewCellWithAutoLayout) that @smileyborg has provided – smee Jan 20 '14 at 15:04