Leaving inputAccessoryView visible after keyboard

2019-02-24 23:59发布

I want to make behavior like messaging app. I have been browsing Stack Overflow for solutions for this, and indeed there are plenty:

Leaving inputAccessoryView visible after keyboard is dismissed

This was the one that I found. But it seems things are a little different in iOS8. If I do the same thing in new iOS8 sdk, i get error:

'UIViewControllerHierarchyInconsistency', reason: 'child view controller:<UICompatibilityInputViewController: 0x7fdcb3441b10> should have parent view controller:<ViewController: 0x7fdcb3b1e9f0> but requested parent is:<UIInputWindowController: 0x7fdcb684c000>'

In order to test this more I made a sample project, just one controller with view on the bottom:

ViewController code

Storyboard

Outlet is connected to bottom view, that only has UITextField on it. Am I missing something and how do i get the desired behvior?

2条回答
Lonely孤独者°
2楼-- · 2019-02-25 00:41

iOS8 has a retain cycle with the inputAccessoryView. Here's a good post that seems to have a good workaround:

http://derpturkey.com/uitextfield-docked-like-ios-messenger/

查看更多
冷血范
3楼-- · 2019-02-25 00:57

You are adding the someView to multiple superViews, which leads to inconsistent hierarchies (which it is telling you).

When the keyboard gets activated, it calls the inputAccessoryView() method to see if it needs to stick anything on top of the keyboard, and adds that to its own superView. But you already added it to the view through your storyboard.

Now there are 2 ways you can solve this:

  1. Make a .xib with your view and return that one in your inputAccessoryView(), not adding it to any superview yourself (the keyboard will.

  2. Or make it completely in code using NSLayoutConstraint.

You can add the following code to your ViewController which will persist the view even when the keyboard is hidden.

override func canBecomeFirstResponder() -> Bool {
    return true
}

Look at this GitHub repo for an example.

查看更多
登录 后发表回答