Gon
Gon

Reputation: 1143

autolayout UILabel's dynamic height calculation doesn't work when text is empty string?

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?

Upvotes: 1

Views: 602

Answers (2)

rushisangani
rushisangani

Reputation: 3395

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;
}

Upvotes: 2

Qing Xu
Qing Xu

Reputation: 2850

[yourLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisVertical];
[yourLabel setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisVertical];

Set your label V compress to a high priority

Upvotes: 0

Related Questions