我正在尝试以编程方式约束 UITextField 但不断收到错误消息“无法激活项的约束,因为它们没有共同的祖先。约束是否在不同的 View 层次结构中引用项?”。
我已将问题缩小到激活约束的位置(即 constraint.active = true)。但是,我不知道如何解决这个问题。
在尝试调试时,我发现在我的 viewDidLoad() 或 viewWillAppear() 中打印出 textField.superview 报告返回 nil,即使我在之前的行中添加了要查看的 textField subview 。最后,如果我只是用 CGRect 初始化 textField,它就可以完美运行。只是不能添加约束。
这些让我真的很困惑。
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
}
最佳答案
您忘记添加 ()
到你的 emailField
结尾声明,因此您创建了一个计算属性,该属性返回一个新的、不同的 UITextField
每次你提到属性(property)。你想要:
var emailField: UITextField {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
return textField
}()
关于ios - 以编程方式约束 UITextField 会导致错误 "Unable to activate constraint because they have no common ancestor.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39736793/