Swift version: 5.0
Navigation bars are one of the most common user interface components in iOS, so being able to add buttons to them is something you'll do a lot. You can add buttons to the left and right side of a navigation bar, and you can add more than one to either side.
Note: usually bar button items don't belong to the
UINavigationBar directly. Instead, they belong to a
UINavigationItem that is currently active on the navigation bar, which in turn is usually owned by the view controller that is currently active on the screen.
So, to create bar button items for your view controller, you would add code like this to the
viewDidLoad() method of a view controller:
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action: #selector(addTapped))
That will call the
addTapped() method on the current view controller when either button is tapped. Note that the first one uses a standard system icon (recommended when it's available!) and the second one uses text.
Like I said, you can attach more than one bar button item to either side of the navigation bar, like this:
let add = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped)) let play = UIBarButtonItem(title: "Play", style: .plain, target: self, action: #selector(playTapped)) navigationItem.rightBarButtonItems = [add, play]
SPONSOR Meet the new Instabug – more than just bug reporting! We help you build better apps and minimize your debugging time. With each bug report, we automatically capture details like network requests, repro steps, and session details. Get real-time crash reports with stack trace details and session data to help you catch and fix issues easily. And with our customizable in-app surveys, you’ll gather insightful user feedback and much more. Instabug is the fastest and easiest way to release with confidence. Start your free trial now! Start your free trial now!
Available from iOS 2.0
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.