kAiN
kAiN

Reputation: 2773

TableViewCell Auto Height on label text

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?

Upvotes: 1

Views: 1223

Answers (1)

smee
smee

Reputation: 371

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.

Upvotes: 2

Related Questions