Thursday, May 30, 2013

UIBarButtonItem initWithImage example in Objective C (iOS).

UIBarButtonItem initWithImage

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]
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.
The style of the item. One of the constants defined in UIBarButtonItemStyle.
The object that receives the action message.
The action to send to target when this item is selected.

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

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

Example of [UIBarButtonItem initWithImage].
- (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 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 example article.