Search code examples
iosobjective-cuitableviewautolayoutnsattributedstring

Which is the best approach among Autolayout or calculating the height using NSAttributedString, to implement dynamic height of an UITableViewCell?


I have followed the tutorial from http://raywenderlich.com/73602/dynamic-table-view-cell-height-auto-layout and implemented the same, but with the release of iOS 8.3, the above tutorial doesn't seem to be working.

Therefore i switched back to the following code which works absolutely fine

-(float)height :(NSMutableAttributedString*)string
{
  NSAttributedString *attributedText = string;

  CGRect rect = [attributedText boundingRectWithSize:CGSizeMake(200, MAXFLOAT)
                                           options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                           context:nil];
  CGSize requiredSize = rect.size;
  return requiredSize.height;
}

and call the same in

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{   
  CGFloat heightOfcell = [self height:[array objectAtIndex:indexPath.row]];
  return heightOfcell;
}

Can someone suggest a better way for doing the same in auto-layout and i am not using StoryBoard?


Solution

  • I would suggest use Autolatyout on cell's content view and give an Estimated Row Height in viewDidLoad like this self.tableView.estimatedRowHeight = 200; However this apporach may not support the Earlier versions of IOS.