Resize table cell according to text length

Some times we need to customize our table cell’s height according to text length. For long text we need to make a bigger cell and vice versa. Here is the method to do this:

1. define you table cell’s size and font:

#define CONST_Cell_height 50.0f
#define CONST_Cell_width 270.0f
#define CONST_textLabelFontSize     16
#define CONST_detailLabelFontSize   14

2. Here is the method to calculate table cell width:

– (int) heightOfCellWithTitle :(NSString*)titleText
andSubtitle:(NSString*)subtitleText
{
CGSize titleSize = {0, 0};
CGSize subtitleSize = {0, 0};

if (titleText && ![titleText isEqualToString:@””])
titleSize = [titleText sizeWithFont:[UIFont boldSystemFontOfSize:16]
constrainedToSize:CGSizeMake(CONST_Cell_width, 4000)
lineBreakMode:UILineBreakModeWordWrap];

if (subtitleText && ![subtitleText isEqualToString:@””])
subtitleSize = [subtitleText sizeWithFont:[UIFont systemFontOfSize:14]
constrainedToSize:CGSizeMake(CONST_Cell_width, 4000)
lineBreakMode:UILineBreakModeWordWrap];

descriptionLabelHeight = subtitleSize.height;

return titleSize.height + subtitleSize.height;
}

3. Use this in your table height for row:

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

NSString *title = @”Yor cell title”;
NSString *subtitle =@”Your cell subtitle”;

int height =  “some constant” + [self heightOfCellWithTitle:title andSubtitle:subtitle]; // some constant is used to adjust cell height. may be zero.

return (height < CONST_Cell_height ? CONST_Cell_height : height);

}

it will resize the table cell according to text size.

!! Enjoy !!

This entry was posted in iOS by Muzammil. Bookmark the permalink.

About Muzammil

Hey Guys, I am Muzammil Mohammad. Having 7 years of experience in iOS development. I am here to share my knowledge with all mobile application developers and those companies who are stuck on development (due to bad quality of code or don't know what to do) or want to know how to build a good mobile app. I believe I am more expert in UI and Architecture design of mobile app. So if you need my helps or assistant for your mobile app projects, Feel free to contact me. I will try my best to improve the quality of your app. Or you can hire me to develop your apps. I’d love to talk with you. Best!

Leave a Reply

Your email address will not be published. Required fields are marked *