Saturday, 15 September 2012

Cell height as per text length: iPhone Development

How to dynamically adjust cell's height as per the text length in iPhone development?

Well today I am going to start with a method that will calculate the cell's height appropriate to the length of text and then adjust the cell's height accordingly in an iPhone development.

The iPhone SDK comes with lots of interesting features and lets you design some of your custom made methods.

I was recently faced with a situation where my text was dynamic and hence I had to display it inside the cell that will automatically expand for the text's size. 
Previously my text would be half chunked! And so I came up with this solution.

Let's get started.

First we get our titles and subtitles for the display screen (If any)

NSString * title = @"Your title";
NSString * subTitle = @"Your Subtitle";

we can add it to the cell's height if we want like this:

[self heightOfCellWithTitle:title andSubtitle:subtitle]
Next we need to over ride the method "heightForRowAtIndexPath":

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

If we are getting our text of the cell dynamically, we can do something like this:
Here we pick the text from our sections located at indexPath.section:

NSString*  dynamicText = [[[sections objectAtIndex:indexPath.section] objectForKey:@"fields"] objectAtIndex:indexPath.row];

Next we define our dynamic text with font and its size, I preferred 12.0f.

dynamicText sizeWithFont:[UIFont systemFontOfSize:12.0f]

What we need next is the most important part, here we code what to expect from our cell when it receives our dynamic text:
We will ask the text to be constrained inside the width of the cell and so we do something like this:

[constrainedToSize:CGSizeMake(220.0, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap].height

We have set the CGFLOAT to MAX and we have also employed a wrap for our text this way it does not get chunked. And hence calculated the height of the dynamic text of the cell.

Finally we apply some constant to the above factor on its height this can be 0 or something. In my case it worked for an accurate 44.0!

So, finally our method code looks like this:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
 NSString*   dynamicText  =[[[sections objectAtIndex:indexPath.section] objectForKey:@"fields"] objectAtIndex:indexPath.row];
    return [ dynamicText  sizeWithFont:[UIFont systemFontOfSize:12.0f] constrainedToSize:
   CGSizeMake(220.0, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap].height + 44.0;
Beautiful isn't it ;)

Hope this helps you as it did helped me. Alright guys keep coming back for more. See u then.
Hasta la vista!


Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Best Web Hosting