Tuesday, June 11, 2013

UIToolbar setBackgroundImage example in Objective C (iOS).

UIToolbar setBackgroundImage

Sets the image to use for the background in a given position and with given metrics.

- (void)setBackgroundImage:(UIImage *)backgroundImage forToolbarPosition:(UIToolbarPosition)topOrBottom barMetrics:(UIBarMetrics)barMetrics

Parameters of [UIToolbar setBackgroundImage]
The image to use for the toolbar background in the position specified by topOrBottom and with the metrics specified by barMetrics.
A toolbar position constant.
A bar metrics constant.

UIToolbar setBackgroundImage example.
if([navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        //iOS 5 new UINavigationBar custom background
        [navigationBar setBackgroundImage:image forBarMetrics: UIBarMetricsDefault];
To realize this, take a look at here iOS 4.3 to iOS 5.0 API Differences and search for "UINavigationBar.h"

Example of [UIToolbar setBackgroundImage].
//toolBar background image set based on iOS version
    [[UIDevice currentDevice] systemVersion];

    if ([[[UIDevice currentDevice] systemVersion] floatValue] > 4.9) {

        //iOS 5
        UIImage *toolBarIMG = [UIImage imageNamed: @"toolBar_brown.png"]; 

        if ([toolBar respondsToSelector:@selector(setBackgroundImage:forToolbarPosition:barMetrics:)]) {
            [toolBar setBackgroundImage:toolBarIMG forToolbarPosition:0 barMetrics:0];

    } else {

        //iOS 4
        [toolBar insertSubview:[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"toolBar_brown.png"]] autorelease] atIndex:0];


UIToolbar setBackgroundImage example.
// Set the background image for PortraitMode
[self.toolbar setBackgroundImage:[UIImage imageNamed:@"Sample.png"]
// and For LandscapeMode
[self.toolbar setBackgroundImage:[UIImage imageNamed:@"Sample.png"]

End of UIToolbar setBackgroundImage example article.