How to Hide Navigation Bar when Keyboard is shown in UIKit

⋅ 2 min read ⋅ UIKit UINavigationBar

Table of Contents

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.

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)

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.


Read more article about UIKit, UINavigationBar, or see all available topic

Enjoy the read?

If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.

Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.

If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.

Become a patron Buy me a coffee Tweet Share
Previous
Swift fileprivate vs private

Learn the difference between two similar access levels in Swift, private and fileprivate.

Next
How to preview SwiftUI Layout without device frame

Learn how to preview SwiftUI view without a distraction of a device frame.

← Home