在 Swift 中以编程方式向 stackView 添加按钮

问题描述:

我尝试在 UIStackView 中以动态/编程方式添加按钮,这些按钮是我使用界面构建器构建的,但是当我运行应用程序时它们没有显示.应该添加的按钮数量通常为 4-6 个.你们能告诉我代码有什么问题吗

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

@Nowonder 我只是重新创建了您想要实现的目标.以下是步骤.

@Nowonder I just recreate what you are trying to achieve. The following are the steps.

  1. Interface Builder 在 vi​​ewController 中添加一个 UIStackView 并添加所需的约束.
  2. 添加以下代码.

  1. Add a UIStackView in viewController from Interface Builder and add required constraints.
  2. 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)  

}

结果如下.

希望有帮助.