Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift custom back button in navigation bar

I am trying to use a custom image for my back button in the navigation bar. I am using the below code, which adds the image, but also keeps the text "Back" in the button. I want to also remove the text. Can I do that?

self.navigationController?.navigationBar.backIndicatorImage = UIImage(named: "icon-back")
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "icon-back")
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
like image 448
asheyla Avatar asked Dec 06 '22 18:12

asheyla


2 Answers

Try code below :-)

func SetBackBarButtonCustom()
{
    //Back buttion
    let btnLeftMenu: UIButton = UIButton()
    btnLeftMenu.setImage(UIImage(named: "back_arrow"), for: UIControlState())
    btnLeftMenu.addTarget(self, action: #selector(UIViewController.onClcikBack), for: UIControlEvents.touchUpInside)
    btnLeftMenu.frame = CGRect(x: 0, y: 0, width: 33/2, height: 27/2)
    let barButton = UIBarButtonItem(customView: btnLeftMenu)
    self.navigationItem.leftBarButtonItem = barButton
}

func onClcikBack()
{
    _ = self.navigationController?.popViewController(animated: true)
}
like image 125
Mitul Marsoniya Avatar answered Jan 02 '23 06:01

Mitul Marsoniya


If you want to add Back button in every UIViewController then you can add the code in UIViewController extension else you can use addBackButton() directly as follows.

extension UIViewController {

    func addBackButton() {
        let btnLeftMenu: UIButton = UIButton()
        let image = UIImage(named: "backButtonImage");
        btnLeftMenu.setImage(image, for: .normal)
        btnLeftMenu.setTitle("Back".localized, for: .normal);
        btnLeftMenu.sizeToFit()
        btnLeftMenu.addTarget(self, action: #selector (backButtonClick(sender:)), for: .touchUpInside)
        let barButton = UIBarButtonItem(customView: btnLeftMenu)
        self.navigationItem.leftBarButtonItem = barButton
    }

    func backButtonClick(sender : UIButton) {
        self.navigationController?.popViewController(animated: true);
    }
}

Make sure you should add the following file "backButtonImage.png" in your app bundle.

Call this method self.addBackButton()in your viewDidLoad method of your custom UIViewController class like this

override func viewDidLoad() {
         super.viewDidLoad()
         self.addBackButton()
 }

Note : if you don't add addBackButton Method in extension then you will need to add this method directly in the class and set target and Selector accordingly.

like image 35
Sudhir kumar Avatar answered Jan 02 '23 07:01

Sudhir kumar