以编程方式的Swift 2.0自动布局约束

时间:2016-01-09 03:32:35

标签: swift autolayout

出于某种原因,我正在使用此代码获得terminating with uncaught exception of type NSException。我只是想在tabbar视图上设置put autolayout约束:

func addCommentView() {
    let commentView = UIView.loadFromNibNamed("AddCommentView")
    view.addSubview(commentView!)

    let leftConstraint = NSLayoutConstraint(item: commentView!, attribute: NSLayoutAttribute.Leading, relatedBy: .Equal, toItem: view,
  attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0)

    let rightConstraint = NSLayoutConstraint(item: commentView!, attribute: NSLayoutAttribute.Trailing, relatedBy: .Equal, toItem: view,
  attribute: NSLayoutAttribute.Trailing, multiplier: 1.0, constant: 0)

   let bottomConstraint = NSLayoutConstraint(item: commentView!, attribute: NSLayoutAttribute.Bottom, relatedBy: .Equal, toItem: view,
  attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0)

   let heightConstraint = NSLayoutConstraint(item: commentView!, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute,
  multiplier: 1.0, constant: 0)

   commentView!.addConstraints([leftConstraint, rightConstraint, bottomConstraint, heightConstraint])

 }

1 个答案:

答案 0 :(得分:1)

你应该编辑:

commentView!.addConstraints([leftConstraint, rightConstraint, bottomConstraint, heightConstraint])

到:

view.addConstraints([leftConstraint, rightConstraint, bottomConstraint, heightConstraint])

崩溃将会消失。但是高度约束呢?