Friday, May 31, 2013

UIBarButtonItem setBackButtonBackgroundImage example in Objective C (iOS).


UIBarButtonItem setBackButtonBackgroundImage


Sets the back button background image for a given control state and bar metrics

- (void)setBackButtonBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics

Parameters
backgroundImage
The image to use for the back button’s background.
state
A control state.
barMetrics
Bar metrics.

Discussion of [UIBarButtonItem setBackButtonBackgroundImage]
This modifier applies only to navigation bar back buttons and is ignored by other buttons.

For good results, backgroundImage must be a stretchable image.

UIBarButtonItem setBackButtonBackgroundImage example.
UIImage *toolbarBtnBg = [[UIImage imageNamed:@\"toolbarBtn_bg.png\"] stretchableImageWithLeftCapWidth:15 topCapHeight:15];
    UIImage *toolbarBtnBgHighlighted = [[UIImage imageNamed:@\"toolbarBtnHiglighted_bg.png\"] stretchableImageWithLeftCapWidth:15 topCapHeight:15];
       
    UIBarButtonItem *addBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@\"iconAdd.png\"] style:UIBarButtonItemStyleBordered target:self action:@selector(addAction:)];
    [addBtn setBackButtonBackgroundImage: toolbarBtnBg forState:UIControlStateNormal barMetrics:0];
    [addBtn setBackButtonBackgroundImage: toolbarBtnBgHighlighted forState:UIControlStateHighlighted barMetrics:0];

Example of [UIBarButtonItem setBackButtonBackgroundImage].
 UIImage *leftButtonImage = [UIImage imageNamed:@"nav-bar-back-button.png"];
    UIImage *leftbuttonNormal = [leftButtonImage
                                 stretchableImageWithLeftCapWidth:15 topCapHeight:15];

    UIBarButtonItem *item = [[[UIBarButtonItem alloc]init] autorelease];
    [item setBackButtonBackgroundImage:leftbuttonNormal forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

    [item setTitle:@"雨松MOMO"];

    self.navigationItem.backBarButtonItem = item;

UIBarButtonItem setBackButtonBackgroundImage example.
int imageSize = 20; //REPLACE WITH YOUR IMAGE WIDTH

UIImage *barBackBtnImg = [[UIImage imageNamed:@"NavBackButton"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, imageSize, 0, 0)];

[[UIBarButtonItem appearance] setBackButtonBackgroundImage:barBackBtnImg
                                                  forState:UIControlStateNormal
                                                barMetrics:UIBarMetricsDefault];

End of UIBarButtonItem setBackButtonBackgroundImage example article.