user3904534
user3904534

Reputation: 319

Swift 2.0 autolayout constraints programmatically

For some reason I'm getting a terminating with uncaught exception of type NSException with this code. I'm just trying to make put autolayout constraints on a tabbar view:

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])

 }

Upvotes: 0

Views: 190

Answers (1)

vien vu
vien vu

Reputation: 4337

You should edit:

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

to:

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

Crash will go. But what about height constraint?

Upvotes: 1

Related Questions