John Doah
John Doah

Reputation: 1999

Can't get StackView to view items properly

I'm trying to add 4 items to a UIStackView, this 4 Items are all a simple square UIView, I added them all to a UIStackView but they won't stay square, it's like the UIStackView squeezes them or something. I tried setting the UIStackView to be the same height of the items, and set it's width to be the height of the items * 4 so I can try and get 1:1 ratio, but nothing worked for me.

The UIView is a simple UIView with background color. I tried to set it's widthAnchor and heightAnchor to 50, but I know the UIStackView has it's own way to size the items in it. I don't really know what to do about this. This is my UIStackView setup and constraints:

Setup:

private lazy var optionButtonStack: UIStackView = {
    let stack = UIStackView(arrangedSubviews: [self.optionButton1, self.optionButton2, self.optionButton3, self.optionButton4])
    stack.translatesAutoresizingMaskIntoConstraints = false
    stack.distribution = .fillEqually
    stack.axis = .horizontal
    stack.spacing = 2.5

    return stack
}()

Constraints:

private func setupOptionButtonStack() {
    addSubview(optionButtonStack)
    NSLayoutConstraint.activate([
        optionButtonStack.heightAnchor.constraint(equalToConstant: 50),
        optionButtonStack.widthAnchor.constraint(equalToConstant: 200),
        optionButtonStack.centerXAnchor.constraint(equalTo: self.centerXAnchor),
        optionButtonStack.bottomAnchor.constraint(equalTo: buyNowButton.topAnchor, constant: -8),
    ])
}

This is the UIView in case this is needed:

private let optionButton1: UIView = {
    let view = UIView()
    view.backgroundColor = .appBlue
    view.translatesAutoresizingMaskIntoConstraints = false
    view.widthAnchor.constraint(equalToConstant: 50).isActive = true
    view.heightAnchor.constraint(equalToConstant: 50).isActive = true
    view.tag = 1

    return view
}()

Upvotes: 0

Views: 33

Answers (1)

matt
matt

Reputation: 535159

Give the button view a single constraint setting its width equal to its height:

view.widthAnchor.constraint(equalTo: view.heightAnchor).isActive = true

and set the stack view alignment at center.

Upvotes: 1

Related Questions