I’m trying to create UIStackView
with 3 UISegmentedControl
with this code, and I want them to be center both vertically and horizontaly:
let segmented = UISegmentedControl(items: ["SOLID","GRADIENT"])
let segmented2 = UISegmentedControl(items: ["SOLID","GRADIENT"])
let segmented3 = UISegmentedControl(items: ["SOLID","GRADIENT"])
segmented.selectedSegmentIndex = 0
segmented2.selectedSegmentIndex = 0
segmented3.selectedSegmentIndex = 0
let st = UIStackView(arrangedSubviews: [segmented, segmented2, segmented3])
st.axis = .vertical
st.spacing = 5;
st.alignment = .center
self.addSubview(st)
st.translatesAutoresizingMaskIntoConstraints = false
st.topAnchor.constraint(greaterThanOrEqualTo: self.topAnchor, constant: 0.0).isActive = true
st.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0.0).isActive = true
st.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0.0).isActive = true
st.bottomAnchor.constraint(greaterThanOrEqualTo: self.bottomAnchor, constant: 0.0).isActive = true
st.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0.0).isActive = true
st.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0.0).isActive = true
The problem is that I get this view:
Any idea how I can fix this problem? I want all of them will be at the same height.
2
Answers
I believe this:
Should be inverted to:
Because you want the y-position of the stack view’s bottom anchor to be a smaller value than the y-position of the view’s own bottom anchor.
In general the constraint constants have to be inverted for the trailing and bottom anchors.
First, because your constraints are using
self
(as inself.topAnchor
), this code must belong to aUIView
subclass.It’s not clear what your end goal is… Do you want the stack of segmented controls to determine the height of the view? Or do you want the control heights to be determined by the height of the view? How are you setting the constraints of the custom view that holds this stack of controls?
In any case, you can get the segmented controls to be equal Heights simply by adding this line:
However, regardless of what else you’re doing, your current constraints for the stack view are probably incorrect.
Try it like this:
No need for either
centerX
orcenterY
constraints.Another way to set those constraints, which is a little more concise and readable, is like this: