ios - 使用 UIViewController 的 View 作为 UITextField 的 inputView 时抛出“UIViewControllerHierarchyInconsistency”

标签 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)
  }
}

如果我在文本字段上点击一次,一切都会按预期工作,显示我的蓝色 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/

相关文章:

ios - swift:一段时间后重复动画

ios - 使用 CAGradientLayer 进行角度/圆渐变

ios - UITextField/UITextView/UISearchBar 上的死锁/硬卡住成为FirstResponder

swift - 字典中元素的加权平均值

objective-c - sizeWithFont 在 UITextField 中返回错误的高度

ios - 如何在 TableView 单元格中添加 12 个文本字段并通过其标签值访问每个文本字段的文本?

iphone - 是否可以调用过去的日期UILocal Notification?

ios - 在 Objective-C 中读取 gzip 压缩字符串失败?

python - 想要使用 python swiftclient 将 sqlite.db 文件上传到 swift 容器并且总是得到 utf-8 错误

swift - "stringByAddingPercentEncodingWithAllowedCharacters"替换了比应有的更多的字符