Search code examples
iosswiftuinavigationcontrolleruinavigationitem

How to make a UIBarButtonItem perform a function when pressed?


I am trying to make a custom back button using this code:

let back = UIImage(named: "header_backarrow")
let backView = UIImageView(image: back)
let backItem = UIBarButtonItem(customView: backView)
navigationItem.leftBarButtonItem = backItem

I want the navigation item to perform this code:

func dismissManual() {
    dismiss(animated: true, completion: nil)
}

I have tried many things like following this Stack Overflow post: Execute action when back bar button of UINavigationController is pressed

I have also tried making it a navigationItem.backBarButtonItem; however, nothing seems to work. Some things show the correct custom image, but do not work as a button; on the other hand, some work as a button, but do not show the correct image.

Does anybody know how I can show the correct image and make the item work as a button? Thanks.


Solution

  • Do it as follows:

    override func viewDidLoad() {
            super.viewDidLoad()
    
            let back = UIImage(named: "header_backarrow")
            let backView = UIImageView(image: back)
            backView.isUserInteractionEnabled = true
            let tap = UITapGestureRecognizer(target: self, action: #selector(dismissManual))
            backView.addGestureRecognizer(tap)
            let backItem = UIBarButtonItem(customView: backView)
            navigationItem.leftBarButtonItem = backItem
        }
    
        @objc func dismissManual() {
            print("print----")
    //        dismiss(animated: true, completion: nil)
        }
    

    Add gesture to backView it will work! It's similiar to this question IOS - Swift - adding target and action to BarButtonItem's customView