[英]Constraining UITextField programmatically leads to error “Unable to activate constraint because they have no common ancestor.”
I'm trying to programmatically constrain a UITextField but keep getting the error, "Unable to activate constraint with items because they have no common ancestor. Does the constraint reference items in different view hierarchies?". 我正在尝试以编程方式约束UITextField,但始终收到错误消息:“由于没有共同的祖先,因此无法使用项目激活约束。约束是否在不同的视图层次结构中引用了项目?”。
I've narrowed the problem to the where I activate my constraint (ie constraint.active = true). 我将问题缩小到激活约束的位置(即constraint.active = true)。 However, I have no idea how to fix the problem. 但是,我不知道如何解决该问题。
While trying to debug, I found that printing out the textField.superview in my viewDidLoad() or viewWillAppear() reports back a nil even though I add the textField subview to view in the line before. 在尝试调试时,我发现在我的viewDidLoad()或viewWillAppear()中打印出textField.superview报告为零,即使我在前面的行中添加了要查看的textField子视图。 Finally, if I just initialize the textField with a CGRect it works perfectly. 最后,如果我只是使用CGRect初始化textField,那么它可以完美地工作。 Just can't add contraints. 只是不能添加约束。
This ones got me really stumped. 这让我真的很困惑。
class SignInController: UIViewController {
var emailField: UITextField {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(emailField)
setupEmailField()
print(view) //Returns <UIView: 0x7f93f6076510; frame = (0 0; 375 667); autoresize = W+H; layer = <CALayer: 0x7f93f607a8d0>>
print(emailField.superview) //Returns nil
}
// Breaks at this function
func setupEmailField() {
emailField.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 50).active = true
emailField.rightAnchor.constraintEqualToAnchor(view.rightAnchor, constant: -10).active = true
emailField.leftAnchor.constraintEqualToAnchor(view.leftAnchor, constant: 10).active = true
emailField.heightAnchor.constraintEqualToAnchor(view.heightAnchor, multiplier: 0.05).active = true
}
You forgot to add the ()
to the end of your emailField
declaration, so you created a computed property that returns a new, different UITextField
each time you refer to the property. 您忘记了在emailField
声明的末尾添加()
,因此您创建了一个计算属性,每次引用该属性时,该属性都会返回一个新的不同的UITextField
。 You want: 你要:
var emailField: UITextField {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.