Reputation: 1303
I have a UIStackView and it displays an UIImageView and a UIButton in vertical alignment. UIImageView will take the complete width of the parent view and the UIButton will be a constant width of 100.
// add button to the screen
let button = UIButton(configuration: config, primaryAction: UIAction() { [weak self] _ in
// do something
})
stackView.addArrangedSubview(imageView)
stackView.addArrangedSubview(button)
view.addSubview(stackView)
// NOT WORKING - THE BUTTON RENDERS AS THE WIDTH OF THE VIEW TAKING THE WHOLE WIDTH OF THE SCREEN
button.widthAnchor.constraint(equalToConstant: 20).isActive = true
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -200).isActive = true
stackView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
stackView.heightAnchor.constraint(equalToConstant: 400).isActive = true
How can I control the width of the UIButton to be 100?
Upvotes: 0
Views: 1533
Reputation: 1895
You must Add Button to another UIView and after that, you should add the view (which contains your button) to Stackview
your button must have constraint.
let buttonContainerView = UIView()
buttonContainerView.addSubView(button)
stackView.addArrangedSubview(imageView)
stackView.addArrangedSubview(buttonContainerView)
view.addSubview(stackView)
Upvotes: 3