I'm adding a stackView in my viewcontroller in this way:
addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.anchor(top: nameLabel.bottomAnchor, leading: leadingAnchor, bottom: bottomAnchor, trailing: trailingAnchor)
let emotionsButton = EmotionButton()
emotionsButton.translatesAutoresizingMaskIntoConstraints = false
let contentButton = ContentsButton()
contentButton.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.alignment = .center
stackView.distribution = .equalCentering
stackView.spacing = 8
stackView.addArrangedSubview(emotionsButton)
stackView.addArrangedSubview(contentButton)
emotionsButton.widthAnchor.constraint(equalToConstant: 91).isActive = true
contentButton.widthAnchor.constraint(equalToConstant: 91).isActive = true
emotionsButton.heightAnchor.constraint(equalToConstant: 83).isActive = true
contentButton.heightAnchor.constraint(equalToConstant: 83).isActive = true
but the result I get is not the desired one; this is what I want:

This is what I get:

UIStackView tries to fill the entire width with its contents. So you have some options here
Since the stackView's content size is based on its content, you should consider getting rid of the leading and trailing anchors and use a horizontal center instead. (You can keep one of them alongside with the center one to prevent it from overlapping the edges)
Another option is to add. dummy views at both sides of the stack view (inside), make them have clear color and let them be the last to hug. So. they. can. fill extra space.
There are other options (like not using the stack view at all) that you can implement to make it happen.
If you want to do it on a stackview, you shouldnt need to configure the heightAnchor or widthAnchor of your subviews(emotionsButton, contentButton) accordingly.. All you need to configure is the height and width anchor for the stackView, and let it resize your subviews accordingly.
stackView.axis = .horizontal
stackView.alignment = .center
stackView.distribution = .equalCentering
stackView.spacing = 8
stackView.widthAnchor.constraint(equalToConstant: 91 * 2).isActive = true
stackView.heightAnchor.constraint(equalToConstant: 83).isActive = true
stackView.addArrangedSubview(emotionsButton)
stackView.addArrangedSubview(contentButton)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With