UIBarButtonItem with UIImage Always Tinted iOS 7

2019-01-16 07:44发布

问题:

I'm trying to add a UIBarButtonItem containing a UIImage to a UIToolbar. The image keeps being tinted and I can't get it to show as the original colored image - all I want to do is display an image, verbatim, in a UIBarButtonItem! I'm following the directions in the iOS 7 transition guide to set the image rendering mode to UIImageRenderingModeAlwaysOriginal.

UIImage *image = [UIImage imageNamed:@"myImage.png"];
image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

UIBarButtonItem *ratingImage = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStyleBordered target:nil action:nil];

[toolbar setItems:[NSArray arrayWithObjects:ratingImage, nil] animated:YES];

One thing to note is that I set the tintColor for the main UIWindow of my app right when it loads...maybe this isn't important with regard to my issue, but thought I'd mention it.

回答1:

I spent an evening trying to figure this out as well. You were very close to the solution. The trick is to instantiate the UIImage with the rendering mode.

Instead of doing:

 UIImage *image = [UIImage imageNamed:@"myImage.png"];
 image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

do this:

 UIImage *image = [[UIImage imageNamed:@"myImage.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

and it works!

In my case, I had dragged a Navigation bar to my viewcontroller in the IB, and added the BarButtonItem. But don't provide the item an image in the IB. Make an outlet and assign it the UIImage (like we created above) by doing this:

[myCustomBarButtonItem setImage:image];

Hope this works for you.



回答2:

UIImageRenderingModeAlwaysOriginal can also be set by selecting the image in your Assets.xcassets "folder" in XCode and setting the "Render as" dropdown to "Original image".



回答3:

For Swift 2.1+ it would look like this:

let image : UIImage? = UIImage(named:"myImage.png")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)

UPDATED Swift 3

let image : UIImage? = UIImage(named:"myImage.png")!.withRenderingMode(.alwaysOriginal)


回答4:

The accepted answer is fine but if you placed the UIBarButtonItem in a storyboard or xib then you can just:

  • Go to the Assets catalog where the image lives
  • Select the image
  • Go to the attributes inspector (cmd-opt-4)
  • Set "Render As" to "Original Image"

Only do this if you want all instances of this image to show up without tinting.



回答5:

If you want it to work for versions of iOS less than v7, you might need to to this:

UIImage *image = [UIImage imageNamed:@"myImage.png"];
@try {
  image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
} @catch (NSException *exception) {
}

Since imageWithRenderingMode: is an iOS 7 method, you'll get an exception if you try and use it with a lesser version.