' UIViewControllerHierarchyInconsistency'使用UIViewController的视图作为UITextField的inputView时抛出

时间:2018-04-10 18:21:20

标签: ios swift uitextfield 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>'

我可能遗漏了一些显而易见的东西,但我无法弄清楚正在发生什么......感谢任何帮助:)

谢谢!

1 个答案:

答案 0 :(得分:2)

问题在于您尝试使用文本字段将另一个视图控制器的视图添加到视图控制器。

尝试以下方法:

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