I want to override self.navigationItem.backBarButtonItem
's target and action,
I tried:
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(backButtonOverrideAction:)];
[self.navigationItem setLeftBarButtonItem:backButton];
it is working but i want to use the default arrow:
i also tried:
UIBarButtonItem *backButton = self.navigationItem.backBarButtonItem;
[backButton setTarget:self];
[backButton setAction:@selector(backButtonOverrideAction:)];
but unfortunately it's not working.. do you have any idea how to do this?
STILL, No direct access for changing target and action on self.navigationItem.backBarButtonItem
.
I ended up using the first one i tried... and get my (custom) image..
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"myImage.png"]
style:UIBarButtonItemStyleBordered
target:self
action:@selector(backButtonOverrideAction:)];
[self.navigationItem setLeftBarButtonItem:backButton];
while...
//this two lines of code are still useless, i just feel sorry for them..
[self.navigationItem.backBarButtonItem setTarget:<#(id)#>];
[self.navigationItem.backBarButtonItem setAction:<#(SEL)#>];
You cannot assign action to back BarButton. The solution for that is to create the custom back button.
In swift 3.1
override func viewDidLoad() {
// set navigationItem.leftBarButtonItem return to Root
let backToRootVCButton = UIBarButtonItem.init(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(backToRootVCAction))
self.navigationItem.setLeftBarButton(backToRootVCButton, animated: true)
}
func backToRootVCAction() {
_ = self.navigationController?.popToRootViewController(animated: true)
}
This works for 11.3:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let BackItemIndex = 2
if let subViews = navigationController?.navigationBar.subviews,
subViews.count > BackItemIndex {
navigationController?.navigationBar.subviews[BackItemIndex].subviews.first?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(doPerformAction(_:))))
}
}
@objc func doPerformAction(_ sender: Any) {
// some code
}
This solution is based on searching the active subviews until the corresponding to backBarButtonItem and then add a UITapGestureRecognizer, so that it captures the event on the element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With