SIAJSAJ IJSAIJSAJA
SIAJSAJ IJSAIJSAJA

Reputation: 327

How can I make views height depend on its content in Swift?

I have got a view and some elements in it

let background_img_view: UIView = {
    let view = UIView()
    return view
}()
background_img_view.addSubview(background_image)
background_img_view.addSubview(border)
background_img_view.addSubview(about_txt)

about_txt size is unknown, it can be 30px or 300px, now I want my background_img_view's height to depend on about_txt's height.

How can I make it happen programmatically?

Upvotes: 1

Views: 384

Answers (1)

Kiran Dwarkan
Kiran Dwarkan

Reputation: 56

Have you tried using the sizeThatFits(_:) method for the about_txt view. Use the size that this function returns and set the superview's size to that. https://developer.apple.com/reference/uikit/uiview/1622625-sizethatfits

If you have the subviews added before the view is on the screen, you could set the height in the viewWillAppear method of your view controller. You can also update the size in viewWillLayoutSubviews. If you're using auto layouts, have a look at setNeedsLayout vs. setNeedsUpdateConstraints and layoutIfNeeded vs updateConstraintsIfNeeded

Upvotes: 1

Related Questions