我花了整整一天的时间来找出与文本字段的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)
}
}
如果我在文本字段上点击一次,一切都会按预期进行,则将显示蓝色视图,而不是键盘。但是,如果我在inputView动画期间在textField上多次点击,则应用程序崩溃,但出现以下异常:
*** 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>'
我可能缺少一些明显的东西,但我不知道发生了什么...感谢您的帮助:)
谢谢!
最佳答案
问题在于您试图将另一个视图控制器的视图添加到带有文本字段的视图控制器中。
请尝试以下操作:
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/