guillaume
guillaume

Reputation: 51

UILabel dynamic height

I know a lot of questions have been asked about it but could not figure out. I have a label that needs its number of lines adusting dynamically. It works with automatic preferred max width, but could not make it work when explicit (I want to support ios7).

The label height does not currently increase

Here is my code:

-(void)viewDidLoad
{
  [super viewDidLoad];
  _feedBackLabel.numberOfLines = 0;
  _feedBackLabel.lineBreakMode = NSLineBreakByWordWrapping;
  _feedBackLabel.preferredMaxLayoutWidth = self.view.frame.size.width - 90;
  [_feedBackLabel setContentHuggingPriority:UILayoutPriorityRequired
                                  forAxis:UILayoutConstraintAxisVertical];
  [_feedBackLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
}

-(void)setFeedback:(NSString*)response
{
  self.feedBackLabel.text = response;
  self.feedBackLabel.hidden = NO;
  [self.feedBackLabel sizeToFit];
}

I have pinned my label with a leading and a trailing space to its superview with priority required. The content hugging and compression resistance are both 750 in the vertical axis. The label has a height constraint with a priority of 500.

Thanks Guillaume

Upvotes: 0

Views: 214

Answers (2)

guillaume
guillaume

Reputation: 51

Actually it was working partially. It was only working for long strings; if the string was just a bit too big for my label then it did not work. What I did is increase my horizontal content hugging priority to 750, i.e. higher than the height priority which is 500 (all other constraints are required), and set the preferredMaxLayoutWidth dynamically, and it works as expected now.

Thanks

Guillaume

Upvotes: 0

Jincy Sam
Jincy Sam

Reputation: 421

Remove height constraint from label and run your code

Upvotes: 1

Related Questions