Question

On my nav bar, I have a couple of rightBarButtonItems that have custom icons (the icon images are white, which worked well with the basic color scheme of iOS 6).

Under iOS 7, loading the images using initWithTitle (see code snippet 1) replaces the "white" color in the icon with the proper global tint (a specific color of dark blue in this case)

Code Snippet 1:

UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] initWithTitle:@"" style:(UIBarButtonItemStyle) UIBarButtonSystemItemCancel target:(self) action:@selector(refreshList)];

refreshButton.image = [UIImage imageNamed:@"RefreshIcon.png"];

However, I needed to use initWithCustomView to overcome a weird change in behavior that was causing the icons to move out of view. The basic idea was to specifically set the size of the icons. initWithCustomView solved the sizing problem, but does not display the button images with the global tint, they are displayed in the color of the image (white). Code Snippet 2 shows how I am creating the button with initWithCustomView.

Code Snippet 2:

CGRect frameCustomButton2 = CGRectMake(0.0, 0.0, 18.0, 18.0);
UIButton *customButton2 = [[UIButton alloc] initWithFrame:frameCustomButton2];
[customButton2 setBackgroundImage:iconRefreshButton forState:UIControlStateNormal];
UIBarButtonItem *barCustomButton2 =[[UIBarButtonItem alloc] initWithCustomView:customButton2 ];
barCustomButton2.image = iconRefreshButton;
[customButton2 addTarget:self action:@selector(refreshList) forControlEvents:UIControlEventTouchUpInside];

All of this code is of course in (void)viewDidLoad. I have tried things like:

barCustomButton2.tintColor = [UIColor blackColor];  //doesn't work

or [barButtonAppearance setTintColor:[UIColor blackColor]]; // doesn't work

and they do not override the white color of the image. It is almost as if the creation of the custom view takes place after the view looks at the global tint color?

How can I ensure the button icon takes on the global tint?

Thanks!

Was it helpful?

Solution

Just wanted to get this into a root comment to give better context to the "answer" checkmark, and give better formatting.

I was able to figure this one out! You can tell the image to always render as template, which will force it to take on the global tint color.

UIImage *iconRefreshButton = [UIImage imageNamed:@"MyIconFilename.png"];
iconRefreshButton = [iconRefreshButton imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];

The default, if you don't set it, is "UIImageRenderingModeAutomatic" which means it will render as a template or original image based on context.

OTHER TIPS

You'll either have to work around the issue you were having with the first code snippet, or you'll have to create a UIButton subclass that uses its image as a mask to show the tint color in drawRect:.

I'd recommend the first approach.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top