Добавление подпрограммы и ее программное программирование с ограничениями

Я добавил UIView, используя IB для контроллера вида. Позвольте называть его 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. Может кто-нибудь, пожалуйста, скажите мне, что мне здесь не хватает?

Спасибо.

Ответы

Ответ 1

Я уверен, вам также нужно установить:

label.setTranslatesAutoresizingMaskIntoConstraints(false)

В противном случае я не думаю, что ограничения будут применяться к метке.

Ответ 2

Примечание для Swift 2/3

Он изменился на свойство Boolean: UIView.translatesAutoresizingMaskIntoConstraints

Вместо этого ранее:

label.setTranslatesAutoresizingMaskIntoConstraints(false)

Теперь это:

label.translatesAutoresizingMaskIntoConstraints = false

Ответ 3

Вам нужно сделать это для каждого UIControl, чтобы назначить NSConstraints

label.translatesAutoresizingMaskIntoConstraints = false