UIStackView is awesome, I love Equal Spacing Distribution. But how to achieve the same space also outside of elements dynamically? In my case all elements will have same ratio 1:1
You can add equal spacing using the story board as shown here:
Source: https://mcmap.net/q/479547/-how-to-add-equal-spacing-and-equal-width-for-button-in-ios-auto-layout
@Declan has the right idea. Here's that answer programatically where you add extra views on either side so the stack view gives correct outside spacing with any number of buttons.
stackView.alignment = .center
stackView.axis = .horizontal
stackView.distribution = .equalCentering
// Then when I add the views...
let leftView = UIView()
stackView.addArrangedSubview(leftView)
content.buttons.forEach { (button) in
stackView.addArrangedSubview(button)
}
let rightView = UIView()
stackView.addArrangedSubview(rightView)
Here's what my view looks like with 2 items using equalSpacing
And here it is with equalCentering
distribution, also a nice look.
I prefer to let the UIStackView
handle the spacing. Create a UIStackView
with equal spacing and add two 0px wide (0px high if using a vertical stackview) transparent views to the the far sides of your stack view.
I think what you want is to have the same spacing outside of the stack view with the spacing outside.
What I would do is the put stack view inside another view (GRAY VIEW) and set the leading and trailing constraint of the stack view to be equal to the spacing of the stack view.
Spacing of the Stack View
Constraints of the Stack View from its super view (Gray View)
You can use constraints and give then same height and width. So when you change the dimension of anyone of the component then all components are changed with same dimension.
© 2022 - 2024 — McMap. All rights reserved.
UIStackView
– Odisodium