Reputation: 950
I created prototype UITableViewCell
with a title and subtitle in UITableView
. Contents in those cells have many word-lines. I'm trying to dynamically set the height of the cells.
The idea/method with sizeFont is deprecated with the latest SDK.
How to dynamically set the height of the cells in a simple way?
I'd be grateful for some advise or a link to a tutorial or even better some coding examples!
Upvotes: 1
Views: 187
Reputation: 3658
To set height for UITableViewCell
use tableView:heightForRowAtIndexPath: method of UITableViewDelegate
.
To calculate UILabel
height in iOS7 you have to use boundingRectWithSize:options:context: of NSString
.
boundingRectWithSize:options:context:
will give you a rectangle needed to draw your UILabel's text.
Try this code:
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
NSString* string = yourLabel.text;
UIFont* font = yourLabel.font;
CGRect expectedLabel =
[string boundingRectWithSize:CGSizeMake(tableView.frame.size.width, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{ NSFontAttributeName : font }
context:nil];
CGFloat verticalOffset = 10;
return verticalOffset + expectedLabelRect.size.height + verticalOffset;
}
Upvotes: 1