When subclassing UIToolBar to have a custom backgr

2019-08-28 17:58发布

I'm subclassing UIToolBar, here is how I override the drawRect method of UIToolBar:

- (void)drawRect:(CGRect)rect
{
    UIImage *backgroundImage = [UIImage imageNamed:@"UIToolBar_Background.png"];
    [backgroundImage drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}

The app uses a UINavigationController paradigm initialized with initWithNavigationBarClass method.

The issue is that the bottom half of toolbar is black? The UIToolBar_Background.png is 44 pixels height (or 88 for retina). It should not have it's bottom half black.

1条回答
Lonely孤独者°
2楼-- · 2019-08-28 18:17

By subclassing UIToolBar and overriding drawRect, you eliminate some of UIToolBar's own drawing. Why not use the appearance api to set a background image:

[[UIToolbar appearance] setBackgroundImage:[UIImage imageNamed:@"UIToolBar_Background.png"]
                        forToolbarPosition:UIToolbarPositionBottom
                                barMetrics:UIBarMetricsDefault];

alternatively, you could use the subclassing route, just make sure you call [super drawrect:rect] before doing your own drawing:

- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    UIImage *backgroundImage = [UIImage imageNamed:@"UIToolBar_Background.png"];
    [backgroundImage drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
查看更多
登录 后发表回答