Is it possible to give a UIToolBar a custom background from an image rather than the usual tinted blue/black fade out?
I\'ve tried giving the view a background and s
Answering my own question here!!! Overriding the drawRect function and creating an implementation of the UIToolbar does the trick :)
@implementation UIToolbar (CustomImage)
- (void)drawRect:(CGRect)rect {
UIImage *image = [UIImage imageNamed: @"nm010400.png"];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end
You can use the Appearance API since iOS5:
[[UIToolbar appearance] setBackgroundImage:[UIImage imageNamed:@"navbar_bg"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
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.
@interface UIToolbar (CustomToolbar) @property (nonatomic, strong) UIView *customBackgroundView; @end
#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
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; }
This is the approach I use for iOS 4 and 5 compatibility:
if ([toolbar respondsToSelector:@selector(setBackgroundImage:forToolbarPosition:barMetrics:)]) {
[toolbar setBackgroundImage:[UIImage imageNamed:@"toolbar-background"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
} else {
[toolbar insertSubview:[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"toolbar-background"]] autorelease] atIndex:0];
}