Hey Readers,

Its been quite a while since i have not written any of the blogs, and today i came across classic iOS development issues so i decided to write a blog for the same.

How to make tableview cell adopt the text height ? There are many places where we need tableview’s cell to adopt the size of the text that might be coming either from web services or from other data source. So how do we do that ?

For implementing Autosizing table view we need to follow these steps 

Step 1 : 

Set following properties on tableview

self.tableView.rowHeight = UITableViewAutomaticDimension;

Step 2 : 

Calculate height for Tableview, for this we need to take our cell’s label’s, textfields and buttons and other elements who will have dynamic heights and we need to calculate their height which is done below by calling heightNeededForText for each of the label, button, textfield and other elements.

-(CGFloat)calculaeHeightForTableViewCell:(CellArticle *)sizingCell{

    CGFloat tmpheight=[self heightNeededForText:sizingCell.txtDesc.text withFont:[UIFont fontWithName:@"Helvetica Neue" size:14.0] width:sizingCell.frame.size.width lineBreakMode:NSLineBreakByWordWrapping] + [self heightNeededForText:sizingCell.txtTitle.text withFont:[UIFont fontWithName:@"Helvetica Neue" size:14.0] width:sizingCell.frame.size.width lineBreakMode:NSLineBreakByWordWrapping];

    CGFloat tmph=MAX(tmpheight, 110);

    CGSize size = CGSizeMake(sizingCell.frame.size.width, tmph);


    return size.height + 10.0;



- (CGFloat)heightNeededForText:(NSString *)text withFont:(UIFont *)font width:(CGFloat)width lineBreakMode:(NSLineBreakMode)lineBreakMode {

    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];

                       paragraphStyle.lineBreakMode = lineBreakMode;

    CGSize size = [text boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)

                                                        options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)

                                                     attributes:@{ NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle }



    return ceilf(size.height);


Step 3 : 

Run the code and you are done.

Hope this helps.

Implementing Auto Sizing Tableview Cell

Aadil Keshwani

People call me geek i call myself Coder. I like to explore & learn new things, R&D and Innovation motivates me. By profession i am iPhone Developer but i have sound knowledge of PhoneGap, HTML, CSS3, WordPress, Photoshop, PHP, CodeIgniter, OpenCart. Feel free to contact me for any queries or help in above technologies, i would be more than happy to help you out.

Category: Uncategorized