在 Swift 中以编程方式向 stackView 添加按钮 [英] Adding buttons programmatically to stackView in Swift

查看:30
本文介绍了在 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)  

}

结果如下.

希望有帮助.

这篇关于在 Swift 中以编程方式向 stackView 添加按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆