问题
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
回答1:
@Nowonder I just recreate what you are trying to achieve. The following are the steps.
- Add a
UIStackView
in viewController fromInterface Builder
and 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) }
Following is the outcome.
Hope it helps.
回答2:
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
translatesAutoresizingMaskIntoConstraints
to false.button1.translatesAutoresizingMaskIntoConstraints = false button2.translatesAutoresizingMaskIntoConstraints = false buttonStackView.translatesAutoresizingMaskIntoConstraints = false
Now 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.
回答3:
SOLVED!
The button showed up when I set the type of the button with the instance method init(type:)
来源:https://stackoverflow.com/questions/58162441/adding-buttons-programmatically-to-stackview-in-swift