How to programmatically create a "Back" UIBarButton item in Swift?

Rami Ammoun picture Rami Ammoun · Dec 15, 2015 · Viewed 36.3k times · Source

I was able to create a UIBarButton item that can go back programmatically using the following code:

    func backAction() -> Void {        
        self.navigationController?.popViewControllerAnimated(true)
    }
override func viewDidLoad() {
        super.viewDidLoad()
    let backButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: "backAction")

        self.navigationItem.leftBarButtonItem = backButton
    }

The problem is that the back button doesn't have the left pointing arrow: enter image description here Is there a way to make it look like a regular back button with the arrow like this: enter image description here

I would also like to know if there is a way to make the button title names as the title of the previous view controller, if that's possible.

Thanks

Answer

sKhan picture sKhan · Dec 15, 2015

Below is the code by using UIButton with image you can add it as a customView for UIBarButtonItem

override func viewDidLoad() {
    super.viewDidLoad()
    var backbutton = UIButton(type: .Custom)
    backbutton.setImage(UIImage(named: "BackButton.png"), forState: .Normal) // Image can be downloaded from here below link 
    backbutton.setTitle("Back", forState: .Normal)
    backbutton.setTitleColor(backbutton.tintColor, forState: .Normal) // You can change the TitleColor
    backbutton.addTarget(self, action: "backAction", forControlEvents: .TouchUpInside)

    self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backbutton)
}

func backAction() -> Void {        
   self.navigationController?.popViewControllerAnimated(true)
}

BackButton.png Download Link

For setting the title of backbutton with the previous view controller title you have to pass the Title as a String while presenting the controller make change to above code as

var titleStrFromPreviousController: String // This value has to be set from previous controller while presenting modal controller
backbutton.setTitle(titleStrFromPreviousController, forState: .Normal)

This may help.

Swift 3

override func viewDidLoad() {
    super.viewDidLoad()

    addBackButton()
}

func addBackButton() {
    let backButton = UIButton(type: .custom)
    backButton.setImage(UIImage(named: "BackButton.png"), for: .normal) // Image can be downloaded from here below link
    backButton.setTitle("Back", for: .normal)
    backButton.setTitleColor(backButton.tintColor, for: .normal) // You can change the TitleColor
    backButton.addTarget(self, action: #selector(self.backAction(_:)), for: .touchUpInside)

    self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
}

@IBAction func backAction(_ sender: UIButton) {
   let _ = self.navigationController?.popViewController(animated: true)
}