azochz azochz - 6 months ago 25
Swift Question

Adding UIBarButton item in swift

I'm trying to add a UIBarButton item to my nav bar.

Here is my Navigation Bar class declaration:

import UIKit

class NavigationBarController: UINavigationController {

override func viewDidLoad() {


override func didReceiveMemoryWarning() {
// Dispose of any resources that can be recreated.

// #pragma mark - Navigation bar data source

func configureToolbar() {
let toolbarButtonItems = [
toolbar.setItems(toolbarButtonItems, animated: true)

var searchBarButtonItem: UIBarButtonItem {
return UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "barButtonItemClicked:")

No error in compiler, but all I get is a plain navigation bar.

How do I get the UIBarButtonItem to show up?


To add items to the NavigationBar of a NavigationController, or a NavigationBar added to a ViewController, you will need to first go through NavigationItem. Try this:

self.navigationItem.setRightBarButtonItems(navigationBarButtonItemsArray, animated: true)

// Or if you just want to insert one item.

self.navigationItem.setRightBarButtonItem(UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "barButtonItemClicked:"), animated: true)

To switch the button to the left side, just replace setRightBarButtonItem to setLeftBarButtonItem or setLeftBarButtonItems.