'UIViewControllerHierarchyInconsistency' 将 UIViewController 的视图用作 UITextField 的 inputView 时抛出
'UIViewControllerHierarchyInconsistency' thrown when using a UIViewController's view as UITextField's inputView
我花了一天的时间试图找出与文本字段的 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
我花了一天的时间试图找出与文本字段的 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