Search code examples
swiftuinavigationbaruibarbuttonitemback-button

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)

Solution

  • 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)
    }