Can I give a UIToolBar a custom background in my iPhone app?
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
UIToolbar inherits from UIView. This just worked for me:
[topBar insertSubview:[[[UIImageView alloc] initWithImage:[UIImage imageNamed:BAR_BKG_IMG]] autorelease] atIndex:0];
Slightly modified version of loreto's answer, which works for me on ios 4 and 5:
// Set the background of a toolbar
+(void)setToolbarBack:(NSString*)bgFilename toolbar:(UIToolbar*)toolbar {
// Add Custom Toolbar
UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:bgFilename]];
iv.frame = CGRectMake(0, 0, toolbar.frame.size.width, toolbar.frame.size.height);
iv.autoresizingMask = UIViewAutoresizingFlexibleWidth;
// Add the tab bar controller's view to the window and display.
if([[[UIDevice currentDevice] systemVersion] intValue] >= 5)
[toolbar insertSubview:iv atIndex:1]; // iOS5 atIndex:1
else
[toolbar insertSubview:iv atIndex:0]; // iOS4 atIndex:0
toolbar.backgroundColor = [UIColor clearColor];
}
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];
}