Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a UIBarButtonItem with a colored image?

I have an image that I want to display on a UIBarButtonItem, but for some reason it only shows the outline of it and the rest is all white. How can I have it actually display the image?

Thanks!

like image 443
DevDevDev Avatar asked Dec 02 '09 19:12

DevDevDev


2 Answers

There's other iOS7+ solution:

NSString *iconFilename = // ... UIImage *image =      [[UIImage imageNamed:iconFilename]          imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]; UIBarButtonItem *barButtonItem =      [[UIBarButtonItem alloc] initWithImage:image                                      style:UIBarButtonItemStylePlain                                      target:self                                      action:@selector(onBarButtonItemTapped:)]; 

Swift 5:

let iconFilename: String = // ... let image = UIImage(named: iconFilename)?.withRenderingMode(.alwaysOriginal) let barButtonItem = UIBarButtonItem(image: image,                                      style: .plain,                                      target: self,                                      action: #selector(onBarButtonItemTapped(_:))) 

Extract from UIImage.h:

... navigation bars, tab bars, toolbars, and segmented controls automatically treat their foreground images as templates ... You can use UIImageRenderingModeAlwaysTemplate to force your image to always be rendered as a template or UIImageRenderingModeAlwaysOriginal to force your image to always be rendered as an original.

like image 133
MANIAK_dobrii Avatar answered Oct 11 '22 12:10

MANIAK_dobrii


UPDATE: See MANIAK_dobrii's answer for an easier solution, available in iOS 7+.


Here is how I use an image for a UIBarButtonItem:

UIImage *image = [UIImage imageNamed:@"buttonImage.png"]; UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.bounds = CGRectMake( 0, 0, image.size.width, image.size.height );     [button setImage:image forState:UIControlStateNormal]; [button addTarget:myTarget action:@selector(myAction) forControlEvents:UIControlEventTouchUpInside];     UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button]; … 
like image 30
amrox Avatar answered Oct 11 '22 14:10

amrox