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

时间:2016-01-11 22:57:50

标签: ios swift nslayoutconstraint

我收到以下错误:

  

添加到视图时,约束的项必须是该视图的后代(或视图本身)。如果在组装视图层次结构之前需要解析约束,则会崩溃。休息 - [UIView(UIConstraintBasedLayout)

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

  

UIViewController.swift

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

同时在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])


}

1 个答案:

答案 0 :(得分:4)

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