Swift以编程方式向superview添加约束

时间:2016-06-14 23:26:53

标签: ios swift nslayoutconstraint ios-autolayout

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

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.

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

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

1 个答案:

答案 0 :(得分:2)

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