Change the UITableViewCell Height According to Amount of Text

Solution 1:

Its simple, just add this to your code:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

It automatically count an height of row and than return a float... :-)

Hope this helps!

Solution 2:

Hi Josh,

Using tableView:heightForRowAtIndexPath: you can give the size of each row at run time. now your problem is how to get height from your string there are function in NSString class by this code your problem,

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
  NSString *str = [dataSourceArray objectAtIndex:indexPath.row];
    CGSize size = [str sizeWithFont:[UIFont fontWithName:@"Helvetica" size:17] constrainedToSize:CGSizeMake(280, 999) lineBreakMode:NSLineBreakByWordWrapping];
    NSLog(@"%f",size.height);
    return size.height + 10;
}

by below line you set your label`s num. of line to max. so set it in cellForRowAtIndexPath: method.

cell.textLabel.numberOfLines = 0;

if you use some custom cell then manage all label`s string with this and get sum of all that height then set the height of your cell.

Edit : iOS 8 onwards if you set proper autolayout constraints to label then you have to set only following delegate method to achieve this.

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
   //minimum size of your cell, it should be single line of label if you are not clear min. then return UITableViewAutomaticDimension;    
   return UITableViewAutomaticDimension; 
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

that`s it. no any calculation required. For more information check this tutorial.

Solution 3:

In your CustomCell: Remember to add the constraint top and bottom for your UILabel

For adjust UILabel height depend on text just change UILabel line to 0 (see the answer here)

Then in your code, just only set 2 line

self.tableView.estimatedRowHeight = 80;
self.tableView.rowHeight = UITableViewAutomaticDimension;

Here is my custom cell
enter image description here Here is my UILabel constraints
enter image description here
The screen you will achieve

enter image description here

=== Suggestion ===
IF your cell has some UILabels and Images (not like my example) then:

  • You should put all UILabels and Images to one GroupView (View)
  • Add the constraint top and bottom to supper view for this GroupView (like the UILabel in my image)
  • Adjust UILabel height like the my suggestion above
  • Adjust the GroupView height depend on the content (the content is all UILabels and Images)
  • Finally, change estimateRowHeight and tableView.rowHeight like the code above

Hope this help