添加子视图并以编程方式使用约束对其进行定位

时间:2014-11-03 19:47:19

标签: ios swift uiview uilabel autolayout

我已将IB UIView添加到视图控制器上。我们称之为redView

enter image description here

然后我在代码中使用自动布局约束固定了它的所有四个方面,当我运行它时,它看起来像预期的那样。

enter image description here

现在我想以编程方式向此视图添加UILabel,并使用自动布局约束将其放置在中心。

以下是我到目前为止的代码。

import UIKit

class ViewController: UIViewController {

    @IBOutlet private var redView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        redView.setTranslatesAutoresizingMaskIntoConstraints(false)

        let leadingConstraint = NSLayoutConstraint(item: redView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 0)
        let trailingConstraint = NSLayoutConstraint(item: redView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: 0)
        let topConstraint = NSLayoutConstraint(item: redView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0)
        let bottomConstraint = NSLayoutConstraint(item: redView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0)
        view.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])


        let label = UILabel()
        label.text = "Auto Layout Exercise"
        redView.addSubview(label)

        let xCenterConstraint = NSLayoutConstraint(item: label, attribute: .CenterX, relatedBy: .Equal, toItem: redView, attribute: .CenterX, multiplier: 1, constant: 0)
        let yCenterConstraint = NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: redView, attribute: .CenterY, multiplier: 1, constant: 0)
        let leadingConstraint1 = NSLayoutConstraint(item: label, attribute: .Leading, relatedBy: .Equal, toItem: redView, attribute: .Leading, multiplier: 1, constant: 20)
        let trailingConstraint1 = NSLayoutConstraint(item: label, attribute: .Trailing, relatedBy: .Equal, toItem: redView, attribute: .Trailing, multiplier: 1, constant: -20)
        redView.addConstraints([xCenterConstraint, yCenterConstraint, leadingConstraint1, trailingConstraint1])

    }

}

问题是标签没有出现在redView上。谁能告诉我我在这里失踪了什么?

谢谢。

3 个答案:

答案 0 :(得分:37)

我很确定你还需要设置:

label.setTranslatesAutoresizingMaskIntoConstraints(false)

否则我认为约束不适用于标签。

答案 1 :(得分:13)

注意Swift 2/3

它已更改为布尔属性:UIView.translatesAutoresizingMaskIntoConstraints

而不是以前:

label.setTranslatesAutoresizingMaskIntoConstraints(false)

现在是:

label.translatesAutoresizingMaskIntoConstraints = false

答案 2 :(得分:3)

您需要为每个UIControl指定NSConstraints

label.translatesAutoresizingMaskIntoConstraints = false