Assume that I have a ViewControllerA
that points to ViewControllerB
, I can set the title of Back button in ViewControllerB
via this in ViewControllerA
:
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil) //set title to blank
navigationController?.pushViewController(destinationVC, animated: true)
However, how can I replace the image? I tried this but I still only see the default "Back" image, instead of a custom image:
navigationItem.backBarButtonItem = UIBarButtonItem(image: UIImage(named: "back-toolbar"), style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
I want to use this image:
After reading many other SO posts, I don't want to implement a leftButtonItem
for each destination view like ViewControllerB
and have to manage the back Action and swipe left gesture.
I also can't set the image in AppDelegate because I use one image for some views and another image for other views.
UPDATE:
Per @rounak's tip, I was able to set the backBarButton, but the position seems wrong. Any way to adjust it?
You can just set the backIndicatorImage
:
navigationController?.navigationBar.backIndicatorImage = UIImage(named: "back")
navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "back")
This will apply the indicator image only for that navigation controller, rather than all navigation controllers in your app. You can change this image inside your view controller in viewWillAppear
/viewWillDisappear
for view controllers that need a different back image.
There's no need to set the leftButtonItem
for each view controller. You can replace the image via the appearance property selectors of UINavigationBar
which will set the default back indicator image for the whole app.
Here's an example in Objective-C, i'm sure you can easily find it's Swift equivalent:
[[UINavigationBar appearance] setBackIndicatorImage:[UIImage imageNamed:@"back-toolbar.png"]];
[[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:[UIImage imageNamed:@"back-toolbar.png"]];
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