视图布局模糊

问题描述 投票:-1回答:1

以编程方式我正在尝试使用自动布局创建带有5个按钮的堆栈视图。当我运行项目然后它运行没有显示任何错误但它没有显示按钮堆栈。

另一方面,它在Debug View Hierarchy中显示“View has ambiguous layout”。我在这里失踪了什么。

class TestView: UIView {
var stackView = UIStackView()
override init(frame: CGRect) {
    super.init(frame: frame)
    initComponents()
}
func initComponents() {
    self.autoresizesSubviews = false
    stackView.autoresizesSubviews = false
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.distribution = .equalSpacing
    stackView.axis = .horizontal
    stackView.alignment = .fill
    stackView.contentMode = .scaleToFill
    addSubview(stackView)
    NSLayoutConstraint.activate([
        stackView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
        stackView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
        stackView.topAnchor.constraint(equalTo: self.topAnchor),
        stackView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
        ])
    for i in 0...4 {
        let button = UIButton()

        button.titleLabel?.text = "\(i)"
        button.translatesAutoresizingMaskIntoConstraints = false

        stackView.addSubview(button)

        button.heightAnchor.constraint(equalTo: stackView.heightAnchor, multiplier: 1).isActive = true
        button.widthAnchor.constraint(equalTo: button.heightAnchor, multiplier: 1).isActive = true
    }
}
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}}

在ViewController.swift文件中

let frame = CGRect(x: 0, y: 0, width: 200, height: 30)
    let test = TestView.init(frame: frame)
    self.view.addSubview(test)
ios swift uibutton autolayout uistackview
1个回答
0
投票

我不得不改变一些事情来完成这项工作:

  1. 使用button.setTitle(_:for:)设置按钮的标题。
  2. 使用button.setTitleColor(_:for:)为文本设置颜色。
  3. 设置按钮的背景颜色。
  4. 使用stackView将按钮添加到stackView.addArrangedSubview(button)

此外,您可能希望将帧向下移动一点。它位于左上角,位于状态栏的顶部,位于iPhone X的凹槽后面。


for i in 0...4 {
    let button = UIButton()

    button.setTitle("\(i)", for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = false

    // Set these colors to whatever you like
    button.setTitleColor(.black, for: .normal)
    button.backgroundColor = .red

    stackView.addArrangedSubview(button)

    button.heightAnchor.constraint(equalTo: stackView.heightAnchor, multiplier: 1).isActive = true
    button.widthAnchor.constraint(equalTo: button.heightAnchor, multiplier: 1).isActive = true
}
© www.soinside.com 2019 - 2024. All rights reserved.