Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backBarButtonItem image in iOS 8

Tags:

ios

swift

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)

enter image description here

I want to use this image:

enter image description here

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?

enter image description here

like image 480
netwire Avatar asked May 02 '15 13:05

netwire


2 Answers

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.

like image 103
rounak Avatar answered Nov 19 '22 23:11

rounak


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"]];
like image 37
Artal Avatar answered Nov 19 '22 23:11

Artal