- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSAttributedString *aString = [self.rows objectAtIndex:indexPath.row];
CGRect r = [aString boundingRectWithSize:CGSizeMake(self.tableView.bounds.size.width, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin context:nil];
r.size.height += 50.0f;
return r.size.height;
}
My self.rows contain NSAttributedString's which have different sizes. Some consist of just a single word and some consist of several lines (containing newline characters) I need to add 50.0f to the height because otherwise my cells do not show all the content of the longer texts.
The problem is that if the text contains only a single word I get much to much padding. My table cell consists of just a label with the following auto layout:
@"V:|[customLabel]|"
@"H:|-[_customLabel]-|"
What am I doing wrong?
Not sure what you're doing wrong, but in my own code I've got a UITextView in the row and I do this:
// tableView:cellForRowAtIndexPath:
BOOL iPad = [UIDevice currentDevice].userInterfaceIdiom != UIUserInterfaceIdiomPhone;
CGFloat width = tableView.frame.size.width - (iPad ? 86 : 16);
CGSize idealSize = [textView sizeThatFits:CGSizeMake(width, FLT_MAX)];
textView.frame = CGRectMake(10, 1, width, idealSize.height);
// tableView:heightForRowAtIndexPath:
[self tableView:tableView cellForRowAtIndexPath:indexPath]; // make sure the text view exists is calculated.
return [textView frame].size.height + 4;
That code literally took me days of research to get right, and it works. Having table rows with an unknown height is not as easy as it seems at first glance.