【问题标题】:View has ambigous layout视图有不明确的布局
【发布时间】:2018-12-05 19:11:09
【问题描述】:

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

另一方面,在 Debug View Hierarchy 中,它显示 “View 的布局不明确。”我在这里缺少的内容。

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】:

    我必须改变一些东西才能使它工作:

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

    此外,您可能希望将框架向下移动一点。它位于左上角,位于状态栏上方,位于 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
    }
    

    【讨论】:

      猜你喜欢
      • 2013-09-27
      • 2013-10-15
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      • 2013-10-27
      • 1970-01-01
      • 2014-07-18
      • 1970-01-01
      相关资源
      最近更新 更多