Swift 以编程方式向超级视图添加约束

Swift add constraint to superview programmatically

我想添加一些简单的约束,但总是出现这样的错误:

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.

我的想法是将选择器视图添加到 table 视图中。当用户单击 table 项时,此选择器视图将显示。这是我的代码:

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)
     }
}
self.view.addConstraint(topContrain)
self.view.addConstraint(bottomContrain)