Ios NSGenericeException以编程方式添加某些约束时
这是我的代码Ios NSGenericeException以编程方式添加某些约束时,ios,swift,Ios,Swift,这是我的代码 func showMessageView(){ let leftConstraint = messageView.leftAnchor.constraintEqualToAnchor(self.view.leftAnchor) let bottomConstraint = messageView.bottomAnchor.constraintGreaterThanOrEqualToAnchor(self.view.bottomAnchor) let high
func showMessageView(){
let leftConstraint = messageView.leftAnchor.constraintEqualToAnchor(self.view.leftAnchor)
let bottomConstraint = messageView.bottomAnchor.constraintGreaterThanOrEqualToAnchor(self.view.bottomAnchor)
let highConstratin = messageView.heightAnchor.constraintEqualToConstant(44.0)
let widthConstraint = messageView.widthAnchor.constraintGreaterThanOrEqualToAnchor(self.view.widthAnchor)
NSLayoutConstraint.activateConstraints([leftConstraint, bottomConstraint, highConstratin, widthConstraint])
self.view.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(messageView)
}
我收到了这个例外:
由于未捕获的异常“NSGenericeException”而终止应用程序,原因:“无法激活项的约束,并且因为它们没有共同的祖先。”。约束是否引用不同视图层次结构中的项?这是违法的。”
我解决了我的问题,只需将messageView首先添加到视图中,如下所示:
func showMessageView(){
self.view.addSubview(messageView)
let leftConstraint = messageView.leftAnchor.constraintEqualToAnchor(self.view.leftAnchor)
let bottomConstraint = messageView.bottomAnchor.constraintGreaterThanOrEqualToAnchor(self.view.bottomAnchor)
let highConstratin = messageView.heightAnchor.constraintEqualToConstant(44.0)
let widthConstraint = messageView.widthAnchor.constraintGreaterThanOrEqualToAnchor(self.view.widthAnchor)
NSLayoutConstraint.activateConstraints([leftConstraint, bottomConstraint, highConstratin, widthConstraint])
self.view.translatesAutoresizingMaskIntoConstraints = false
}