3

How to Hide Navigation Bar when Keyboard is shown in UIKit

 1 year ago
source link: https://sarunw.com/posts/hide-navigation-bar-when-keyboard-appears/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Keyboard is one of the largest UI components in iOS. It took almost half of your screen assets.

That's maybe the reason UINavigationController offer a way to hide both a navigation bar and toolbar when the keyboard appears.

A navigation bar is hidden when the keyboard appears.

A navigation bar is hidden when the keyboard appears.

How to Hide Navigation Bar when Keyboard is shown in UIKit

To hide navigation controller bars when the keyboard appears, we set the hidesBarsWhenKeyboardAppears property to true.

You set this value on a UINavigationController instance.

let nav = UINavigationController(rootViewController: MyViewController())
nav.hidesBarsWhenKeyboardAppears = true

You can also set this value from a view controller.

override func viewDidLoad() {
super.viewDidLoad()

navigationController?.hidesBarsWhenKeyboardAppears = true
}

Since it is a navigation controller's property, setting it to true will enable the behavior on any view controller under the navigation controller.

You can easily support sarunw.com by checking out this sponsor.

Turn your code into a snapshot:

Sponsor sarunw.com and reach thousands of iOS developers.

Caveats

Dismissing a keyboard won't bring back the bars

Setting the hidesBarsWhenKeyboardAppears property to true will hide bars when the keyboard appears, but dismissing the keyboard won't bring back the bars.

Dismissing the keyboard won't bring back the bars.

Dismissing the keyboard won't bring back the bars.

To mitigate this, you must manually show them when you dismiss the keyboards.

This is the code to bring back the bars.

navigationController?.setNavigationBarHidden(false, animated: true)
navigationController?.setToolbarHidden(false, animated: true)

Not sure if this is a bug or intended behavior. But the fact that it still there since iOS 8, I think we are going to live with it.

We can't revert the change

Another pitfall in this API is once you set hidesBarsWhenKeyboardAppears to true, the behavior will forever persist.

You can't unset it with hidesBarsWhenKeyboardAppears = false.

Again, I think we are going to live with it.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK