Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set UIView size to fit subViews

Tags:

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.

like image 267
Nikolaj Simonsen Avatar asked Sep 16 '16 08:09

Nikolaj Simonsen


People also ask

How do I get UIView size?

If you want to get the view's size: float viewWidth = view. Frame. Width; float viewHeight = view.

What does sizeToFit do?

The function sizeToFit is used when you want to automatically resize a label based on the content stored within it. As you can see, there is no change as the text is perfectly fitting in labelOne. sizeToFit only changes the label's frame.

What is UIView in Swift?

The UIView class is a concrete class that you can instantiate and use to display a fixed background color. You can also subclass it to draw more sophisticated content.

When can I call sizeToFit?

Call this method when you want to resize the current view so that it uses the most appropriate amount of space. Specific UIKit views resize themselves according to their own internal needs. In some cases, if a view does not have a superview, it may size itself to the screen bounds.


1 Answers

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

like image 134
miOS Avatar answered Nov 09 '22 05:11

miOS