Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic table cell height with Autolayout iOS 6 +

I have UITableviewCell subclass. In that cell, I have 2 labels (lblComment and lblDateTimeStampe) and one view to show rating stars. I want dynamic height of lblComment to fit all the text. It should expand & shrink in height depending on the length of comment. I have implemented this before but WITHOUT AutoLayout like below

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  {  

    NSString *label =  self.userComment.commentText;
    CGSize stringSize = [label sizeWithFont:[UIFont boldSystemFontOfSize:15]
                          constrainedToSize:CGSizeMake(320, 9999) 
                              lineBreakMode:UILineBreakModeWordWrap];

    return stringSize.height+10;

} 

Now I am using AutoLayout feature.

How can I achieve this using Autolayout?

Any kind of help is appreciated. Thanks

like image 781
iOSAppDev Avatar asked Jan 28 '13 13:01

iOSAppDev


1 Answers

Unfortunately Auto Layout won't help you with tableView:heightForRowAtIndexPath. You still have to implement that method.

You can use UIView's systemLayoutSizeFittingSize: method but that means you'd have to instantiate and configure a table view cell which can be quite costly. You could keep one off-screen though and reuse it for calculations. But at this point, you don't really save much in terms of development effort, so doing the calculations as you did before manually is probably the best/fastest way to do this.

like image 139
Adrian Schönig Avatar answered Oct 17 '22 21:10

Adrian Schönig