I've tried to add buttons dynamically/programmatically in UIStackView that I've built with interface builder but they failed to show up when I run the application. The number of buttons that's supposed to be added ranging normally from 4-6. Can you guys tell me what's wrong with the code
-
Probably some sizing issues.Mojtaba Hosseini– Mojtaba Hosseini2019-09-30 06:31:01 +00:00Commented Sep 30, 2019 at 6:31
-
I've already set the size & constraint of the stackView using the Interface Builder. @MojtabaHosseinileeebirdy– leeebirdy2019-09-30 06:33:46 +00:00Commented Sep 30, 2019 at 6:33
-
1Do not add Solved to title.matt– matt2019-09-30 06:59:20 +00:00Commented Sep 30, 2019 at 6:59
3 Answers
@Nowonder I just recreate what you are trying to achieve. The following are the steps.
- Add a
UIStackViewin viewController fromInterface Builderand add required constraints. Add the following code.
override func viewDidLoad() { super.viewDidLoad() let button = UIButton() button.setTitle("btn 1", for: .normal) button.backgroundColor = UIColor.red button.translatesAutoresizingMaskIntoConstraints = false let button2 = UIButton() button2.setTitle("btn 2", for: .normal) button2.backgroundColor = UIColor.gray button2.translatesAutoresizingMaskIntoConstraints = false let button3 = UIButton() button3.setTitle("btn 3", for: .normal) button3.backgroundColor = UIColor.brown button3.translatesAutoresizingMaskIntoConstraints = false buttonStackView.alignment = .fill buttonStackView.distribution = .fillEqually buttonStackView.spacing = 8.0 buttonStackView.addArrangedSubview(button) buttonStackView.addArrangedSubview(button2) buttonStackView.addArrangedSubview(button3) }
Hope it helps.
Comments
I think you need to do few more steps before the button will start showing up.
Add the stack view to current view's subviews
view.addSubview(buttonStackView)Now each of these views buttons, as well as the stackView, needs to set the
translatesAutoresizingMaskIntoConstraintsto false.button1.translatesAutoresizingMaskIntoConstraints = false button2.translatesAutoresizingMaskIntoConstraints = false buttonStackView.translatesAutoresizingMaskIntoConstraints = falseNow set the stackView contraints
NSLayoutConstraint.activate([ buttonStackView.topAnchor.constraint(equalTo: view.topAnchor), buttonStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor), buttonStackView.bottomAnchor.constraint(equalTo: view.bottomAnchor), buttonStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor)])You will need to provide the constraints, or can override the intrinsic size of stackView.
override func intrinsicContentSize() -> CGSize { return CGSizeMake(200, 40) }
As UILabel have the intrinsic size and so, the button will show, if not you will have to set the constraints for them also to be safe.



