20
votes

I'm having a UIView that's containing two UILabels, which have dynamic heights. I want the UIView to fit the size of the UILabels + some padding. Right now I'm drawing the labels and then sets the UIView's width and height constraints to the combined size of the labels.

Right now I'm doing this:

func populateWithMessage(headline: String?, message: String) {
    // Sets text
    self.headerLabel.text = headline
    self.messageLabel.text = message

    self.headerLabel.sizeToFit()
    self.messageLabel.sizeToFit()

    self.layoutSubviews()

    // Finding the label with the greatest width
    var longestLabel: UILabel!
    if self.headerLabel.frame.width > self.messageLabel.frame.width {
       longestLabel = self.headerLabel
   } else {
       longestLabel = self.messageLabel
   }
   
   let combinedLabelHeight = self.headerLabel.frame.height + self.messageLabel.frame.height
   
   // Update the container view's constraints
   self.containerViewWidtConstraint.constant = longestLabel.frame.width + 10
   self.containerViewHeightConstraint.constant = combinedLabelHeight + 10

   self.updateConstraints()
}

Unfortunately it doesn't work. I'm using Swift 2.3 and Autolayout.

2
This answer might be usefull stackoverflow.com/questions/16009405/…Carien van Zyl
Thanks for your answer but from what I can tell, that question is on how to make a UILabel fit it's text, not how to make a UIView fit a UILabel.Nikolaj Nielsen
sorry, it didn't help, I tried it out quickly myself and added an answer.Carien van Zyl

2 Answers

37
votes

You can do it using the storyboard itself.

Set the View's bottom constraint to second UIlabel. So when the height of label increases, UIView's height will also increases.

enter image description here

enter image description here

4
votes

@Girish M answer is correct. Just to clarify. Set the top label's constraint to the views' top, vertical spacing between the two labels and a bottom constraint between the bottom label and UIView. Do not set any height constraints.

Alternatively, if you want a bit more control over the heights of the UILabels, you can add height constraints in storyboard for the labels and create outlets for them in your code. Perform this code when changing the text of the labels.

    label1.sizeToFit()
    label2.sizeToFit()

    label1HeightConstraint.constant = label1.frame.size.height
    label2HeightConstraint.constant = label2.frame.size.height

    view.layoutSubviews()