Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top