MonkeyBonkey
MonkeyBonkey

Reputation: 47851

creating a UIToolbar programmatically

I wish to add a UIToolbar programmatically to a view when a user clicks on a button (in my case when they zoom in on a photo).

It seems to work fine when I create the toolbar in the click method and add to the subview but if I create the toolbar in the viewDidLoad method, assign it to an instance variable,and add that instance variable later to the subview on click, nothing appears. The debugger shows that the instance variable is a UIToolbar and is not null. I didn't want to create and destroy the same toolbar on every click so I thought it was better just to keep it as an instance variable that I add and remove from the view as needed. Is this the right approach?

Why is it visible in the one case and not the other.

Setup

@synthesize toolBar;

- (UIToolbar*)createToolbar
{
    UIToolbar* toolbar = [[UIToolbar alloc] init];
    toolbar.frame = CGRectMake(0, self.view.frame.size.height - 44, self.view.frame.size.width, 44); 
    UIBarButtonItem *shareButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(sharePhoto:)];
    NSArray *buttonItems = [NSArray arrayWithObjects:shareButton,nil];
    [toolbar setItems:buttonItems];
    return toolbar;

}

This works

- (void) clickMyButton {

    toolBar = [self createToolbar];
    [self.view addSubview:toolBar];
}

This doesn't show anything

- (void)viewDidLoad
{
    [super viewDidLoad];
 toolBar = [self createToolbar];

}
- (void) clickMyButton {

    [self.view addSubview:toolBar];
}

Why doesn't it work in the latter case

Upvotes: 1

Views: 5656

Answers (1)

Cezar
Cezar

Reputation: 56322

The problem is that when viewDidLoad gets called, it is not guaranteed that the frames for your view and subviews are set. Try calling [self createToolbar] from viewWillAppear or viewDidAppear instead.

Upvotes: 2

Related Questions