Thursday, May 30, 2013

UIBarButtonItem initWithImage style target action example in Objective C (iOS).


UIBarButtonItem initWithImage style target action

Initializes a new item using the specified image and other properties.

- (id)initWithImage:(UIImage *)image style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action

Parameters of [UIBarButtonItem initWithImage style target action]
image
The item’s image. If nil an image is not displayed.
The images displayed on the bar are derived from this image. If this image is too large to fit on the bar, it is scaled to fit. Typically, the size of a toolbar and navigation bar image is 20 x 20 points. The alpha values in the source image are used to create the images—opaque values are ignored.
style
The style of the item. One of the constants defined in UIBarButtonItemStyle.
target
The object that receives the action message.
action
The action to send to target when this item is selected.

Return Value of [UIBarButtonItem initWithImage style target action]
Newly initialized item with the specified properties.

UIBarButtonItem initWithImage style target action example.
UIBarButtonItem *systemItem1 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"image.png"] style:UIBarButtonItemStylePlain target:self action:@selector(pp:)];

Example of [UIBarButtonItem initWithImage style target action].
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"My title";

        UIBarButtonItem *myButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"myimage.png"] style:UIBarButtonItemStylePlain target:self action:@selector(myButtonTapped:)];
        self.navigationItem.rightBarButtonItem = myButton;
        [myButton release];
    }
    return self;
}

UIBarButtonItem initWithImage style target action example.
UIImage *backButtonImage = [UIImage imageNamed:@"backbutton.png"];
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithImage:backButtonImage style:UIBarButtonItemStylePlain target:self.navigationController action:@selector(popViewControllerAnimated:)];
[self.navigationController setHidesBackButton:YES];
[self.navigationItem setLeftBarButtonItem: customItem];
[customItem release];

End of UIBarButtonItem initWithImage style target action example article.