Search code examples
iphonecocoa-touchios4uitoolbar

How to programmatically render a flat background UIColor as the background for a UIToolbar?


So I followed a tutorial which allows me to subclass UIToolbar and draw an image as a custom background for the UIToolbar.

Code was something like this:

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    UIImage *backgroundImage = [UIImage imageNamed:@"toolbar_background.png"];
    [backgroundImage drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}

This works flawlessly. Considering though that I just want my toolbar background to be a flat color. Basically something like [UIColor blackColor], is there an easier way to do this in the drawRect method?

Having to make a 320 x 44 px height flat black background image and use that with the above code seems like extreme overhead when [UIColor blackColor] is available? I'm just not sure how to implement it here.

I thought about doing something like this instead:

- (void)drawRect:(CGRect)rect
{
  UIView *test = [[UIView alloc] initWithFrame:CGRectMake(0,0,self.frame.size.width,self.frame.size.height)];

  test.backgroundColor = [UIColor blackColor];
  [self addSubview:test];
}

But this doesn't work because then the UIView COVERS all the UIToolbar items that I add later i.e the Toolbar is black yes, but the black is overtop all the toolbar items so they are not visible.

Is there a workaround?

Thanks.


Solution

  • Override the -drawRect: method as in your first example, but instead of drawing an image, use the UIRectFill method, like this:

    [[UIColor blackColor] setFill];
    UIRectFill(self.bounds);