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!
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.
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]; …
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With