19

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.

halfer
  • 18,701
  • 13
  • 79
  • 158
Nikolaj Nielsen
  • 1,445
  • 2
  • 15
  • 31

2 Answers2

36

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

miOS
  • 1,339
  • 12
  • 18
4

@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()
Carien van Zyl
  • 2,705
  • 19
  • 27