以编程方式添加时,应用程序在 NSLayoutConstraint 上崩溃

App is crashing on NSLayoutConstraint when added programmatically

我收到以下错误:

When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView(UIConstraintBasedLayout)

基本上我想要一个 200h x 200w 的蓝色视图,它位于屏幕中间。

UIViewController.swift

override func loadView() {
    super.loadView()
    self.view = View()
}

Meanwhile in the View.swift

class View: UIView {
var blueView : UIView?

convenience init() {
    // also tried  UIScreen.mainScreen().bounds
    self.init(frame:CGRectZero)
    self.backgroundColor = UIColor.redColor()
    self.setupView()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init:coder")
}

override init(frame: CGRect) {
    super.init(frame: frame)
}

func setupView() {
    self.blueView = UIView()
    self.blueView?.backgroundColor = UIColor.blueColor()
    self.blueView?.translatesAutoresizingMaskIntoConstraints = false
    // self.translatesAutoresizingMaskIntoConstraints = false
    self.addSubview(self.blueView!)

    let centerXConstraint = NSLayoutConstraint(
        // object that we want to constrain
        item: self.blueView!,
        // the attribute of the item we want to constraint
        attribute: NSLayoutAttribute.CenterX,
        // how we want to relate this item with another item so most likely its parent view
        relatedBy: NSLayoutRelation.Equal,
        // this is the item that we are setting up the relationship with
        toItem: self,
        attribute: NSLayoutAttribute.CenterX,
        // How much I want the CenterX of BlueView to Differ from the CenterX of the self
        multiplier: 1.0,
        constant: 0)

    let centerYConstraint = NSLayoutConstraint(
        item: self.blueView!,
        attribute: NSLayoutAttribute.CenterY,
        relatedBy: NSLayoutRelation.Equal,
        toItem: self,
        attribute: NSLayoutAttribute.CenterY,
        multiplier: 1.0,
        constant: 0)

    // These work but the previous two don't
    let widthContraint = NSLayoutConstraint(
        item: self.blueView!,
        attribute: NSLayoutAttribute.Width,
        relatedBy: NSLayoutRelation.Equal,
        toItem: nil, 
        attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0,
        constant: 200)

    let heightConstraint = NSLayoutConstraint(
        item: self.blueView!,
        attribute: NSLayoutAttribute.Height,
        relatedBy: NSLayoutRelation.Equal,
        toItem: nil, 
        attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0,
        constant: 200)

    self.blueView?.addConstraints([widthContraint, heightConstraint, centerXConstraint, centerYConstraint])


}

高度和宽度约束属于它们所属的视图。居中和定位属于该视图的父级,因此您必须将这两个添加到父级,而不是视图本身。