Search code examples
iosswiftautolayout

Set UIView to change its height according to Subviews


I'm creating a popup and I have set the popup view height but I want the popup height to adjust automatically to its subviews

What it looks like on Iphone 8: screenshot 1

and what it look like on Iphone 5s: screenshot 2

i want the popup view to resize automatically to fit subview correctly

I'm using this:

let popUpViewWidth = (view.frame.width / 1.4) + 10
    let popUpViewHeight = view.frame.height / 1.8

    popUpView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    popUpView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    popUpView.widthAnchor.constraint(equalToConstant: popUpViewWidth).isActive = true
    popUpView.heightAnchor.constraint(equalToConstant: popUpViewHeight).isActive = true

I know that I have set the fixed size to popUpView, But how can I make changes to make it to change height dynamically, Thanks.

Note: I'm not using any storyboard so plz do not suggest answers related to storyboard and sorry for my bad english


Solution

  • Easy way is to embed all your sub-views in a vertical stack-view. StackView Automatically sets it width and height with respect to its subViews.