Sunday, February 03, 2013

Use an image as your UIBarButtonItem

Using an image as your UIBarButtonItem in your navigationcontroller bar can only be achieved by using a common UIButton as the BarButtonItem's custom view.

This is an example on how you can achieve that. It takes a target, selector and image name and returns a UIBarButtonItem as an image.

+(UIBarButtonItem*) getBarButton:(id)target withSelector:(SEL)selector andImage:(NSString*)imageName
{
    //Create image
    UIImage *image = [UIImage imageNamed:imageName];
    
    //Create UIButton with the imag
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.bounds = CGRectMake(0, 0, image.size.width, image.size.height);
    [button setImage:image forState:UIControlStateNormal];
    [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];

    //Create UIBarButtonItem with customview button
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    return barButton;
}

2 comments:

tom said...

nice

essaykings.co.uk said...

This proved out to be extremely useful in terms of home assignment at the university! I like the idea of your blog very much!