I wanted to add a horizontal stack view to my application so I can have a scoring mechanism for an image.
I created a private method in the StackView
class that would generate a UIButton
with dimensions of 44x44 within my stack view but it seems that the UIButton
fills in the entirety of the stack view instead.
I made sure to programmatically create constraints for the UIButton
within my private method, and tried adjusting the constraints within the storyboard pane, but to no avail. I have attached images of what I'm referring to below.
Any help would be much appreciated!
This happens because the constraints you set for your UIButton
make it unable to satisfy conflicting constraints.
Xcode specifies conflicting constraints under this piece of code in Debugger:
[LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
A possible workaround is to add your UIButton
into a UIView
:
let button = UIButton()
button.backgroundColor = .red
button.translatesAutoresizingMaskIntoConstraints = false
button.widthAnchor.constraint(equalToConstant: 40).isActive = true
button.heightAnchor.constraint(equalToConstant: 40).isActive = true
let viewButton = UIView()
viewButton.addSubview(button)
stack.addArrangedSubview(viewButton)
This would result in something like this (for this example I've set viewButton.backgroundColor
to gray):