Tuesday, June 11, 2013

UIToolbar setBackgroundImage forToolbarPosition barMetrics example in Objective C (iOS).

UIToolbar setBackgroundImage forToolbarPosition barMetrics

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 forToolbarPosition barMetrics]
backgroundImage
The image to use for the toolbar background in the position specified by topOrBottom and with the metrics specified by barMetrics.
topOrBottom
A toolbar position constant.
barMetrics
A bar metrics constant.

UIToolbar setBackgroundImage forToolbarPosition barMetrics 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 forToolbarPosition barMetrics].
//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 forToolbarPosition barMetrics example.
// Set the background image for PortraitMode
[self.toolbar setBackgroundImage:[UIImage imageNamed:@"Sample.png"]
                                   forBarMetrics:UIBarMetricsDefault];
// and For LandscapeMode
[self.toolbar setBackgroundImage:[UIImage imageNamed:@"Sample.png"]
                                   forBarMetrics:UIBarMetricsLandscapePhone];

End of UIToolbar setBackgroundImage forToolbarPosition barMetrics example article.