Swift 自动布局多个 views/labels

Swift autolayout multiple views/labels

我想以编程方式将我的屏幕分成三部分。每个部分应是一个带有背景颜色的标签,宽度设置为:

// Get the device width
self.view.bounds.width  

高度必须是动态的。下图是一个例子。每种颜色都是一个部分。第一部分(红色部分)必须连接到顶部,最后一部分(橙色)必须连接到底部。并根据每个部分内的标签尺寸调整高度。

蓝色部分始终为 100%,并且取决于从蓝色部分中减去的红色和橙色部分。

有人知道如何实现这个吗?感谢帮助!

要做到这一点最好使用AutoLayout,使用NSLayoutConstraints。这是一些示例代码(目前这一切都在 viewDidLoad 中,这可能不是最好的做法,但我会留给您来组织代码。)

override func viewDidLoad() {
    super.viewDidLoad()

    //  1.
    var topView: UIView = self.view

    // Have as many labels as you want!
    for i in 0..<numberOfLabels {
        let label = UILabel()

        //  2.
        label.numberOfLines = 0
        label.setTranslatesAutoresizingMaskIntoConstraints(false)
        self.view.addSubview(label)

        //  3.
        if i == 0 || i == numberOfLabels - 1 {
            label.setContentHuggingPriority(UILayoutPriority.abs(1000), forAxis: UILayoutConstraintAxis.Vertical)
        }

        let widthConstraint = NSLayoutConstraint(item: label, attribute: .Width, relatedBy: .Equal, toItem: self.view, attribute: .Width, multiplier: 1.0, constant: 0.0)
        //  4.
        let heightConstraint = NSLayoutConstraint(item: label, attribute: .Height, relatedBy: .GreaterThanOrEqual, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 20.0)

        //  5.
        let attribute: NSLayoutAttribute = i == 0 ? .Top : .Bottom
        let topConstraint = NSLayoutConstraint(item: label, attribute: .Top, relatedBy: .Equal, toItem: topView, attribute: attribute, multiplier: 1, constant: 0)

        //  6.
        if i == numberOfLabels - 1 {
            let bottomConstraint = NSLayoutConstraint(item: label, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1, constant: 0)

            self.view.addConstraint(bottomConstraint)
        }

        label.addConstraint(heightConstraint)

        self.view.addConstraint(widthConstraint)
        self.view.addConstraint(topConstraint)

        topView = label
    }
}

1. topViewlabelNSLayoutAttribute.Top 相关的视图。例如:第一个标签的顶部与其容器视图相关;第二个标签的顶部与第一个标签相关;第三个标签的顶部与第二个视图相关,依此类推。

2. 将行数设置为零以允许 label.text.

所需的行数

3.设置上下标签的内容拥抱优先级为1000。这将导致顶部和底部标签 'hug' 文本,因为默认情况下,中间标签的拥抱优先级为 250.

4. 创建一个 NSLayoutConstraintlabel 设置为高于 20 点,因为要自动设置 preferredMaxLayoutWidth标签的宽度和高度必须由 NSLayoutConstraints.

明确定义

5. 这将选择 topView 上的属性,该属性会将 label 固定到 topView。例如:如果创建第一个 label,它的顶部被固定到容器视图的顶部。否则,label 的顶部固定到其上方标签的底部。

6. 如果它是最后一个标签,将其底部边缘固定到容器视图的底部。

结果如下:

希望这能回答您的问题。