以编程方式填充 UIStackView

fill a UIStackView programmatically

我在 StoryBoard 中设计了一个 UIStackView,并添加了 2 个高度限制设置为 70 的 UIbutton。 我的堆栈视图设置为垂直填充,并在故事板上设置了一些约束以适合控制器的视图。

我已经从 stackView 和 UIbutton 添加了一个插座。 我正在尝试以编程方式在堆栈视图中添加第三个 UIButton

@IBOutlet weak var Btn1: UIButton!

@IBOutlet weak var myStackView: UIStackView!

var accounts = [Account]()

override func viewDidLoad() {
    super.viewDidLoad()
    Btn1.setTitle("Name", for: .normal)

    let Btn3 = UIButton(frame: CGRect(x: 0, y: 110, width: 100, height: 50))
    Btn3.setTitle("Btn3", for: .normal)
    Btn3.heightAnchor.constraint(equalToConstant: 70).isActive = true
    myStackView.addArrangedSubview(Btn3)

但 Btn3 从未出现

好吧,假设您的背景颜色是 default-white,按钮就在那里,只是很难看到 ;)。换句话说:它的标题颜色是白色。

尝试设置一些颜色:

Btn3.backgroundColor = UIColor.yellow
Btn3.setTitleColor(UIColor.red, for: .normal)

如果您关心的话,您也可以将其创建为系统按钮tintColor:

let Btn3 = UIButton(type: .system)

如果您使用 init(frame:) 创建一个按钮,您会得到一个自定义按钮并且 the tintColor documentation 是这样说的:

This property has no default effect for buttons with type custom. For custom buttons, you must implement any behavior related to tintColor yourself.

此外,在使用 init(frame:) 初始化按钮时,我建议使用 .zero:

,而不是指定无意义的框架(无论如何布局由堆栈视图管理)
let Btn3 = UIButton(frame: .zero)

关于 Swift 命名约定的最后说明:

Follow case conventions. Names of types and protocols are UpperCamelCase. Everything else is lowerCamelCase.

所以 Btn3 表示一个类型,而 btn3loginButton 表示一个变量。请参阅 Swift API 设计指南中的“Follow case conventions”。