I want to put two views into a UIStackView. I want the top item to always be 30% of the space no matter what device (or orientation) that it appears. Thus, I want to have the bottom view to be 70%. How do I tell a UIStackView that I want to use a percentage?
Just set a constraint for the top view.
In the storyboard's Document Outline control-drag from the top view to the stack view and select Equal heights
. This will make their heights equal. Now go to the Size Inspector and you should see the constraint. Double click on it and set the multiplier to 0.3. Then update the frames.
If the bottom view doesn't automatically size or it gives you an error telling that you need a height constraint, just repeat the process, but now set the multiplier to 0.7.
Swift 5.2
To implement this programmatically
Setting UIView
to always be 30% of the size of it's superview within a UIStackView
viewA.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.3).isActive = true
Full code implementation:
// Configure the StackView
let stackView = UIStackView()
stackView.axis = .vertical
stackView.distribution = .fill
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
// Configure View A
let viewA = UIView()
viewA.backgroundColor = .darkGray
viewA.translatesAutoresizingMaskIntoConstraints = false
// Configure View B
let viewB = UIView()
viewB.backgroundColor = .lightGray
viewB.translatesAutoresizingMaskIntoConstraints = false
// Add Views to StackView
stackView.addArrangedSubview(viewA)
stackView.addArrangedSubview(viewB)
// Set the height percentage multiplier to View A
viewA.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.3).isActive = true
From apple documentation
UIStackViewDistributionFillProportionally A layout where the stack view resizes its arranged views so that they fill the available space along the stack view’s axis. Views are resized proportionally based on their intrinsic content size along the stack view’s axis.
So according to this you should set UIStackView
distribution
property to UIStackViewDistributionFillProportionally
and set intrinsic size
, its.
You can get more info here and on Intrinsic content size
© 2022 - 2024 — McMap. All rights reserved.