1

I have looked around quite a bit and can't seem to get working a custom image in my toolbar. I have the code below in the custom initialization section of my ViewController.m, is this the correct place to add this? I don't see any image show in the upper toolbar. I would like to place this on the right hand upper side of the view.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
    UIImage *image = [UIImage imageNamed:@"camera_30_30.png"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:image forState:UIControlStateNormal];

    button.frame = CGRectMake( 0, 0, image.size.width, image.size.height);
    button.showsTouchWhenHighlighted = YES;

    [button addTarget:self action:@selector(myAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

    NSMutableArray *items = [[NSMutableArray alloc] init];
    [items addObject:barButtonItem];
    self.toolbarItems = items;
}
return self;
}

Thanks for looking.

brianhevans
  • 1,183
  • 4
  • 15
  • 28

1 Answers1

2

This may be related to when you assign the toolbarItems. I assume this will need to be set inside the viewDidLoad method once the UI has been loaded.

You could probably also simplify the bar button creation with this:

UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]initWithImage:@"camera_30_30.png" style:UIBarButtonItemStyleBordered target:self action:@selector(myAction)];

Also, in your code, you need to release items at the end

K1w1Geek
  • 605
  • 5
  • 5
  • No need to release if you're using ARC – jsd Aug 31 '12 at 00:32
  • @K1w1Geek, thanks for the assistance but I am in the same boat.... I am not able to add this icon button to the upper right side of my application. Can you provide some more help. I tried your suggestion and no results. – brianhevans Sep 05 '12 at 19:26
  • The upper right will mean you are adding to a navigation bar, not the toolbar. This is how you do that, in the UIViewController viewDidLoad method self.navigationItem.rightBarButtonItem = barButtonItem; – K1w1Geek Oct 17 '12 at 20:44