Tuesday, February 9, 2016

Objective C UITableViewCell height based on content

Usually we set a height for table view cell in the heightForRowAtIndexPath delegate method. If our content text is more on the textLabel, we go for the middle or tail truncation of the text. When user clicks on the cell we open a view and display the full content generally.

What If you got a requirement like, we have to show all the content without any truncations in the cell. In this case the challenge is, cell height should be dynamic based on the content length. In this post let's see how we can achieve this functionality.


                         



From iOS 7.0 we have boundingRectWithSize string method, which gives us the frame required for a string based on the below factors.


  • Maximum width of the label in which we are going to display our text.
  • The label font type and size that we are using.



  
  NSString *message = @"-----LONG CONTENT HERE-----";

  CGSize maximumLabelSize = CGSizeMake(IS_IPA?300-80:180-80, CGFLOAT_MAX);
    
  CGRect textRect = [message boundingRectWithSize:maximumLabelSize

                                             options:NSStringDrawingUsesLineFragmentOrigin| 
                                                         NSStringDrawingUsesFontLeading

                                             attributes:@{NSFontAttributeName:
                                             [UIFont fontWithName:@"Verdana" size:14]context:nil];                                                                                     


    
Use the above logic in your heightForRowAtIndexPath delegate method and take height from the frame that is given by the boundingRectWithSize method.


Hope this post is useful. Fell free to comment in case of any queries.