Search code examples
iosswiftnslayoutconstraintios-autolayout

Swift add constraint to superview programmatically


I would like to add some simple constraint but always get error like this:

Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to install constraint on view. Does the constraint reference something from outside the subtree of the view? That's illegal.

My idea is adding a picker view into a tableview. When the user click on table item this picker view will show. Here is my code:

class InscriptionTableViewController: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource {

     var pickView:UIPickerView!

     override func viewDidLoad() {
         pickView = UIPickerView()
         pickView.delegate = self
         pickView.dataSource = self
         pickView.hidden = true
         pickView.backgroundColor = UIColor.whiteColor()
         self.view.addSubview(pickView)

         let topContrain = NSLayoutConstraint(
             item: pickView,
             attribute: NSLayoutAttribute.Top,
             relatedBy: NSLayoutRelation.Equal,
             toItem: self.view,
             attribute: NSLayoutAttribute.Top,
             multiplier: 1,
             constant: 0)
         let bottomContrain = NSLayoutConstraint(
             item: pickView,
             attribute: NSLayoutAttribute.Bottom,
             relatedBy: NSLayoutRelation.Equal,
             toItem: self.view,
             attribute: NSLayoutAttribute.Bottom,
             multiplier: 1,
             constant: 0)
         pickView.addConstraint(topContrain)
         pickView.addConstraint(bottomContrain)
     }
}

Solution

  • self.view.addConstraint(topContrain)
    self.view.addConstraint(bottomContrain)