You can do this with a category that basically adds a new property to UIToolBar. Overriding drawRect
can work but it's not necessarily future proof. That same strategy for custom UINavigationBar
stopped working with iOS 6.
Here's how I'm doing it.
.h file
@interface UIToolbar (CustomToolbar)
@property (nonatomic, strong) UIView *customBackgroundView;
@end
.m file
#import "CustomToolbar.h"
#import
static char TIToolbarCustomBackgroundImage;
@implementation UIToolbar (CustomToolbar)
- (void)setCustomBackgroundView:(UIView *)newView {
UIView *oldBackgroundView = [self customBackgroundView];
[oldBackgroundView removeFromSuperview];
[self willChangeValueForKey:@"tfCustomBackgroundView"];
objc_setAssociatedObject(self, &TIToolbarCustomBackgroundImage,
newView,
OBJC_ASSOCIATION_RETAIN);
[self didChangeValueForKey:@"tfCustomBackgroundView"];
if (newView != nil) {
[self addSubview:newView];
}
}
- (UIView *)customBackgroundView {
UIView *customBackgroundView = objc_getAssociatedObject(self, &TIToolbarCustomBackgroundImage);
return customBackgroundView;
}
@end
In your view controller code, e.g. viewDidLoad
if (self.navigationController.toolbar.customBackgroundView == nil) {
self.navigationController.toolbar.customBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigation_bar_background.png"]];
self.navigationController.toolbar.customBackgroundView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
}