1

in iOS 8, I have a UILabel in a UITableViewCell. I want the cell to have dynamic height according to UILabel's text. It works fine. But when the text is a empty string, it seems has a default height, but I want it to be zero.

Here is what I've done:

  1. set cell's constraints using masonry. set top, bottom constraint.
  2. set tableView.estimatedHeight
  3. return UITableViewAutomaticDimension for heightForRow delegate method

So did I do anything wrong? Any help?

Gon
  • 1,135
  • 12
  • 22
  • [cell setNeedsUpdateConstraints]; [cell updateConstraintsIfNeeded]; add this two method also set labelcentral vertically so you dont need to give top and bottom space so you have to set leading space to margin from where u required – Rushang Prajapati Dec 30 '15 at 13:01

2 Answers2

2

Change your code for heightForRowAtIndexPath to this. This works!

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

   NSString *text = [yourDataSourceArray objectAtIndex:indexPath.row];
   if(text.length > 0 ){
     return UITableViewAutomaticDimension;
   }

   return 0;
}
rushisangani
  • 3,195
  • 2
  • 14
  • 18
0
[yourLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisVertical];
[yourLabel setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisVertical];

Set your label V compress to a high priority

Qing Xu
  • 2,704
  • 2
  • 22
  • 21