Search code examples
iosuinavigationcontrolleruitoolbaruicolor

iOS - [UIColor clearColor] and UIToolbars


I've been attempting to use [UIColor clearColor] with UIToolbar in an attempt to make a custom control interface more fitting of a "Mechanical" application (Think buttons you would see in a Movie from the 70s).

What is happening is that when I set the toolbar to clearColor it is turning it matte black. The image behind it is red, tan and black so I'm sure it's not working as intended.

One difference I see is that I'm using the toolbar on a nav controller and not a stand alone UIToolbar.

The lines of code are

self.navigationController.toolbar.translucent = YES;
self.navigationController.toolbar.backgroundColor = [UIColor clearColor];

and my upper navigation bar (that is setup in another view) is UIBarStyleBlackTranslucent, could this be throwing it off?

any help tracking this down would be great.


Solution

  • You can set a transparent background for the toolbar of your navigation controller with the following code:

    // UIToolbar.h
    @interface UIToolbar (Transparency)
    - (void)drawRect:(CGRect)rect;
    @end
    // UIToolbar.m
    #import "TransparentToolbar.h"
    @implementation UIToolbar (Transparency)
    - (void)drawRect:(CGRect)rect {
        [[UIColor clearColor] set];
        CGContextFillRect(UIGraphicsGetCurrentContext(), rect);
    }
    @end
    

    Usage:

    // bar_bottom_bumped.png is a toolbar image with transparency
    UIImage *bg = [UIImage imageNamed:@"bar_bottom_bumped.png"];
    UIImageView *background = [[UIImageView alloc] initWithImage:bg];
    background.frame = self.navigationController.toolbar.bounds;
    background.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    BOOL isIOS5 = [[[UIDevice currentDevice] systemVersion] intValue] >= 5;
    self.navigationController.toolbar.backgroundColor = [UIColor clearColor];
    [self.navigationController.toolbar insertSubview:background atIndex: (isIOS5 ? 1 : 0)];