我花了一天时间试图找出与文本字段的 inputView 相关的应用程序崩溃问题。我尝试制作一个测试项目来重现崩溃。这是我所拥有的:
class ViewController: UIViewController {
let keyboardVC = KeyboardViewController()
override func viewDidLoad() {
super.viewDidLoad()
keyboardVC.view.backgroundColor = .blue
let textField = UITextField()
textField.inputView = keyboardVC.view
textField.backgroundColor = .red
view.addSubview(textField)
}
}
如果我在文本字段上点击一次,一切都会按预期工作,显示我的蓝色 View 而不是键盘。但是,如果我在 inputView 动画期间多次点击文本字段,应用程序会崩溃并出现以下异常:
*** Terminating app due to uncaught exception
'UIViewControllerHierarchyInconsistency', reason: 'child view
controller:<Test.KeyboardViewController: 0x7ff53c008f20> should have
parent view controller:<UICompatibilityInputViewController:
0x7ff539403a40> but requested parent is:<UICompatibilityInputViewController: 0x7ff53940e330>'
我可能错过了一些明显的东西,但我不知道发生了什么......任何帮助表示赞赏:)
谢谢!
最佳答案
问题在于您正在尝试将另一个 View Controller 的 View 添加到带有文本字段的 View Controller 。
尝试以下操作:
let inputView = UIView(frame: CGRect(x:0,y:0,width:keyboardVC.view.frame.width, height: keyboardVC.view.frame.height))
inputView.addSubview(keyboardVC.view)
addChildViewController(keyboardVC)
keyboardVC.didMove(toParentViewController: self)
textField.inputView = inputView
关于ios - 使用 UIViewController 的 View 作为 UITextField 的 inputView 时抛出“UIViewControllerHierarchyInconsistency”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49760557/