jjjjjjjj
jjjjjjjj

Reputation: 4493

Multi-Colored back button in UINavigationBar

I have a UINavigationbar in a UINavigationController. I am trying to set the back button to a custom image that I am drawing via core graphics. The image looks fine when placed in a UIImageView, but when I try to place the image as my back button, it appears all as one color. I think this is related to the tintColor property of UINavigationBar.

Basically, no matter what I do, I cannot get 2 colours to show up in the UIImage. This is the image I am trying to set as my back button (just the red circle, not surrounding black):

enter image description here

Here is my code:

let image = Icons.backButton(with: CGSize(width: 28, height: 28))
self.navigationController?.navigationBar.backIndicatorImage = image
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = image
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItem.Style.plain, target: nil, action: nil)

As far as I can tell, when I assign an image to the back button, the navigationBar takes the current tintColor and applies that to the whole image. Alpha channels are allowed, but everything that is solid coloured is filled in with the tint color. So now I am getting a red circle, with no white arrow. I tried setting the tintColor to UIColor.clear, but that made the whole back button clear/invisible.

Is there some way to hack the navigation controller so I can have a back button with more than 1 color? I know I could just set up a custom UIView instead of the using the navigationController, but would prefer not to.

Any help is appreciated. Thanks!

Upvotes: 0

Views: 200

Answers (1)

beyowulf
beyowulf

Reputation: 15321

You need to set the rendering mode to .alwaysOriginal For example:

var backImage = UIImage(named: "back")
backImage = backImage?.withRenderingMode(.alwaysOriginal)
navigationController?.navigationBar.backIndicatorImage = backImage
navigationController?.navigationBar.backIndicatorTransitionMaskImage = backImage

Upvotes: 1

Related Questions