Monday, June 10, 2013

UITabBar setBackgroundImage example in Objective C (iOS).


UITabBar setBackgroundImage

The background image for the bar.

@property(nonatomic, retain) UIImage *backgroundImage

Discussion of [UITabBar setBackgroundImage]
A stretchable background image is stretched, a non-stretchable background image is tiled.

UITabBar setBackgroundImage example.
Like mentioned before on iOS 5 I would suggest you use the background image:

UITabBar *tabBar = tabController.tabBar;
if ([tabBar respondsToSelector:@selector(setBackgroundImage:)]) {
    tabBar.backgroundImage = [UIImage imageNamed:@"TabBackground.png"];
}

Example of [UITabBar setBackgroundImage].
// UITabBar+Custom.m

#import "UITabBar+Custom.h"
#import <QuartzCore/QuartzCore.h>

-(void)setTabBarBackground:(UIImage *)backgroundImage  {
     if([self respondsToSelector:@selector(setBackgroundImage:)]) {
          // ios 5+
          [self setBackgroundImage:backgroundImage];
     }  else  {
          // ios 3.x / 4.x
          self.layer.contents = (id)backgroundImage.CGImage;
     }
}

UITabBar setBackgroundImage example.
// not supported on iOS4   
UITabBar *tabBar = [tabController tabBar];
if ([tabBar respondsToSelector:@selector(setBackgroundImage:)])
{
    // set it just for this instance
    [tabBar setBackgroundImage:[UIImage imageNamed:@"tabbar_brn.jpg"]];

    // set for all
    // [[UITabBar appearance] setBackgroundImage: ...
}
else
{
    // ios 4 code here
}

End of UITabBar setBackgroundImage example article.