Search code examples
swiftuinavigationcontrollerback-button

Invoking the real Back Button Icon - Swift


The code below manages the Back button, but obviously puts the word Back up in lieu of the Icon:

self.navigationItem.hidesBackButton = false
let newBackButton = UIBarButtonItem(title: "Back", style: .Plain, target: self, action: "segueBack")
navigationItem.leftBarButtonItem = newBackButton

How do I get iOS the invoke the back button icon? In Cocoa there was a call along the lines of:

[backButton setImage:[UIImage imageNamed:BACK_BUTTON_DEFAULT_ICON] forState:UIControlStateNormal];

Solution

  • You have to create your own button object in order to set its title. You can initWithTitle or create it and then set the title afterward.

    The backBarButtonItem only affects its child views that are pushed on top of it in the navigation stack. Depending on your design the root view can't be popped any further and can't have a back button. Though, you can affect the leftBarButtonItem.

    Create a UIBarButtonItem instead of setting the title of the existing one.

    For example:

    let newBackButton = UIBarButtonItem (title: "Back", style: .Plain, target: self, action: "segueBack")
    self.navigationItem.backBarButtonItem = newBackButton
    

    Set it on the "parent" view controller, where the Back button will return to.