• How to add a bar button to a navigation bar in Swift

    27 March 2016

    Available from iOS 2.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 as of iOS 5.0 you can add more than one to either side.

    Note: 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 do this:

    navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addTapped")
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .Plain, target: self, action: "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, as of iOS 5.0 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: "addTapped")
    let play = UIBarButtonItem(title: "Play", style: .Plain, target: self, action: "addTapped")
    navigationItem.rightBarButtonItems = [add, play]


Comments closed on this post.