开发者

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 bac开发者_如何学JAVAkground 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.


You can create a flat UIToolbar without the need to create a subclass. Simply set BackgroundColor, BackgroundImage and ShadowImage.

[toolbar setBackgroundColor:[UIColor blackColor]];
[toolbar setBackgroundImage:[[UIImage alloc] init] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
[toolbar setShadowImage:[[UIImage alloc] init] forToolbarPosition:UIToolbarPositionAny];


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜