NEW: Master Swift design patterns with my latest book! >>

How to show and hide a toolbar inside a UINavigationController

Written by Paul Hudson    @twostraws

All navigation controllers have a toolbar built right in, but it's not showing by default. And even if it were showing, it doesn't have any items by default – that's down to you fill in.

To get started, give a view controller some toolbar items by setting its toolbarItems property like this:

let add = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped))
let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)
toolbarItems = [add, spacer]

You can now tell the navigation controller to show its toolbar like this:

navigationController?.setToolbarHidden(false, animated: false)

If you animate between two view controllers with different toolbar items, iOS automatically animates their change.

Available from iOS 3.0 – see Hacking with Swift tutorial 4

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Hacking with watchOS

Transfer your Swift skills to watchOS the easy way, and learn to build real-world apps in the process!

Click here to visit the Hacking with Swift store >>