[ios] 添加一个子视图并以编程方式用约束来定位它



0 Answers

Swift 2/3的注意事项

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

而不是之前的:

label.setTranslatesAutoresizingMaskIntoConstraints(false)

就是现在:

label.translatesAutoresizingMaskIntoConstraints = false
Question

我已经在视图控制器上添加了一个使用IB的UIView 。 我们称之为redView

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

现在我想以编程方式将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 。 任何人都可以告诉我我在这里错过了什么?

谢谢。




Related