I've had this code forever, and it used to work, but it started exhibiting an annoying behavior in, I think, iOS 6. There are several similar threads on SO, but I haven't found a solution that I am comfortable with as of yet. I found a work-around (see below), but it doesn't seem like the "right" way to do it.
Here's a thread with the same issue, but no answers.
When I use an image as a UIBarButtonItem
and put it into a UIToolbar
, the containing rectangle of the UIToolbar
is not entirely transparent. The PNG images that I use for the UIBarButtonItem
are transparent, so that's not the issue. Here is an example:
When I use text instead of an image as the UIBarButtonItem
, transparency is working as expected. As so:
Here is the code that has worked since forever:
NSMutableArray *buttonItems = [[[NSMutableArray alloc] initWithCapacity: 1] autorelease];
UIImage *printButtonImage = [UIImage imageNamed:@"buttonPrint.png"];
UIToolbar *toolBarButtons = [[[UIToolbar alloc] initWithFrame:CGRectMake( 0, 0, 52.0, 44.01 )] autorelease];
UIBarButtonItem *printButton = [[[UIBarButtonItem alloc] initWithImage:printButtonImage style:UIBarButtonItemStyleBordered target:self action:@selector(printDocument:)] autorelease];
[buttonItems addObject:printButton];
[toolBarButtons setItems:buttonItems animated:YES];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:toolBarButtons] autorelease];
According to suggestions from SO, I have added this just prior to [toolBarButtons setItems...]
but it has had no affect:
toolBarButtons.backgroundColor = [UIColor clearColor];
[toolBarButtons setTranslucent:YES];
[toolBarButtons setOpaque:NO];
I found this thread, on which the answer by jd provided a work-around (edited to match my variables):
const float colorMask[6] = {222, 255, 222, 255, 222, 255};
UIImage *img = [[UIImage alloc] init];
UIImage *maskedImage = [UIImage imageWithCGImage: CGImageCreateWithMaskingColors(img.CGImage, colorMask)];
[toolBarButtons setBackgroundImage:maskedImage forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
I have also seen a couple of solutions to this issue that require getting the color of the top or bottom of the navigationController
and applying a gradient, but I refuse to believe that there is no way to make the rectangle of the UIToolbar
entirely transparent, which should allow the navigationController
color to come through, gradient and all.
Is applying a mask image really the only way to simulate the correct UI experience? Has Apple really not provided a way to simply make a UIToolbar
containing rectangle entirely transparent?
For now, I have the correct behavior, but I don't feel like I have the correct solution. This feels like a hack. Does anyone out there know of a better way to accomplish this?