1

I would like to make my UIToolbar solid gray. This has to work for iOS 4.3+

I have subclassed my UIToolbar and added this

- (void)drawRect:(CGRect)rect {

    UIGraphicsBeginImageContext(rect.size);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSaveGState(ctx);

        [[UIColor colorWithRed:64.0f/255.0f
                         green:64.0f/255.0f
                          blue:64.0f/255.0f
                         alpha:1.0f] set];

    CGRect myRect = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    CGContextFillRect(ctx, myRect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGContextRestoreGState(ctx);
    UIGraphicsEndImageContext();

    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}

No way. The toolbar is always black.

any clues?

thanks.

Duck
  • 34,902
  • 47
  • 248
  • 470
  • http://stackoverflow.com/a/5014161/1273175 might be what you are looking for. Use your custom tint color instead of `[UIColor blackColor]` – JamesSwift Oct 24 '12 at 02:48
  • Thanks but I said I want a solid gray bar, not a tinted one... – Duck Oct 24 '12 at 02:59

1 Answers1

7

You could just try using a solid gray background image. You can make a 1x1 pixel gray png image with the color you want. Then use the following code to set it as the background image and it will work on all iOS versions including 4.3 and below.

    UIToolbar *toolBar = //...your toolbar

    UIImage *toolbarBkg = [[UIImage imageNamed: @"toolbarBkg.png"] stretchableImageWithLeftCapWidth:0 topCapHeight:0];

    if ([toolBar respondsToSelector:@selector(setBackgroundImage:forToolbarPosition:barMetrics:)])
        [toolBar setBackgroundImage:toolbarBkg forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
    else {
        UIImageView *background = [[UIImageView alloc] initWithImage:toolbarBkg];
        background.frame = toolBar.frame;
        [toolBar insertSubview:background atIndex:0];
    }
brynbodayle
  • 6,546
  • 2
  • 33
  • 49
  • 1
    To generate the image from a color : ’+ (UIImage *)imageFromColor:(UIColor *)color andSize:(CGSize)size { CGRect rect = CGRectMake(0, 0, size.width, size.height); UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect); UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return img; } – Thomas Decaux Sep 08 '13 at 16:18