Search code examples
iosswiftautolayout

How to programmatically set UIStackView to take up 100% of the width and height of the parent view?


I cannot have constants, as screen sizes would change the stackview height and width. I want to have one general stackview that has the height and width of the view.

problem is if I get self.view.frame.height gives me 0, which is strange, as I thought I could use that to set the height of the stackView.

This works fine with constants, but of course I need it to be dynamic base don the height/width:

parentStack.widthAnchor.constraint(equalToConstant: 414).isActive = true parentStack.heightAnchor.constraint(equalToConstant: 250).isActive = true


Solution

  • You can do this with constraints or with the autoresizing mask.

    If you want to use constraints, you must add the stack view to its superview before activating the constraints, like this:

    let rootView = ...
    rootView.addSubview(parentStack)
    rootView.addSubview(parentStack)
    parentStack.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        rootView.leadingAnchor.constraint(equalTo: parentStack.leadingAnchor),
        rootView.trailingAnchor.constraint(equalTo: parentStack.trailingAnchor),
        rootView.widthAnchor.constraint(equalTo: parentStack.widthAnchor),
        rootView.heightAnchor.constraint(equalTo: parentStack.heightAnchor)])
    

    If you want to use the autoresizing mask, you need to set the stack view's frame equal to its superview's bounds:

    let rootView = ...
    rootView.addSubview(parentStack)
    parentStack.frame = rootView.bounds
    parentStack.translatesAutoresizingMaskIntoConstraints = true
    parentStack.autoresizingMask = [ .flexibleWidth, .flexibleHeight ]