[每当我模拟我的应用程序时,UIButton都不会出现。我收到一个错误消息:
由于未捕获的异常'NSGenericException'而终止应用程序,原因:'无法使用锚点激活约束和因为他们没有共同的祖先。是约束还是它的约束在不同的视图层次结构中锚定参考项?那是非法。'
我该如何解决?
func setView(){
signInButton.addTarget(self, action: #selector(userSignIn), for: .touchUpInside)
signInButton.heightAnchor.constraint(equalToConstant: 120).isActive = true
signInButton.widthAnchor.constraint(equalToConstant: 120).isActive = true
signInButton.setTitle("Sign in",for: .normal)
createAnAccountButton.addTarget(self, action: #selector(createAnAccount), for: .touchUpInside)
createAnAccountButton.setTitle("Create an Account", for: .normal)
createAnAccountButton.heightAnchor.constraint(equalToConstant: 120).isActive = true
createAnAccountButton.widthAnchor.constraint(equalToConstant: 120).isActive = true
let buttonStack = UIStackView()
buttonStack.axis = NSLayoutConstraint.Axis.vertical
buttonStack.distribution = UIStackView.Distribution.equalSpacing
buttonStack.alignment = UIStackView.Alignment.center
buttonStack.spacing = 16
buttonStack.addArrangedSubview(signInButton)
buttonStack.addArrangedSubview(createAnAccountButton)
buttonStack.translatesAutoresizingMaskIntoConstraints = false
buttonStack.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
buttonStack.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
buttonStack.frame = CGRect(x: 0, y: 0, width: 100, height: 60)
self.view.addSubview(buttonStack)
// let barButtonSignIn = UIBarButtonItem(customView: signInButton)
// self.navigationItem.leftBarButtonItem = barButtonSignIn
}
您必须在激活约束之前调用addSubview
。