views:

1585

answers:

1

I have a UINavigationController that gets pushed a DetailsViewController. In this DetailsViewController, I want to use the toolbar that comes with every UINavigationController (atleast, since iPhone OS3.0).

So, in viewDidLoad in my DetailsViewController I create a UIBarButtonItem, I add it to an array and hand it off to the navigation controller:

- (void) viewDidLoad {
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:self action:@selector(selectTemplate)]; 
    NSArray *items = [NSArray arrayWithObject: item];

    TestUIAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    UINavigationController *navController = delegate.navigationController;

    [navController setToolbarItems: items animated:NO];  
    [navController setToolbarHidden: NO animated: YES]; 
}

But, for some reason, while the UIToolbar is animated on to screen, the item is not added to the toolbar.

Is there some sort of specific order things have to be done with the UIToolbar for this to work?

P.S.: the application is in (forced) landscape mode and the navigationController.view has a rotation transform on it. Could that have anything to do with it ?

+3  A: 

Have done some more digging and debugging and I've come to the conclusion that my approach of trying to modify the navigationController was wrong. Instead I should've simply set the toolbarItems property of the DetailsViewController.

After that, my code worked fine:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
     UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemBookmarks target:self action:@selector(selectTemplate)];

     NSArray *myToolbarItems = [[NSArray alloc] initWithObjects: item, nil];   
     [self setToolbarItems: myToolbarItems];
     [myToolbarItems release];

    }
    return self;
}
MathieuK
Short comment -- that UIBarButtonItem allocation looks like it will get leaked. You should probably set it to autorelease.
Shaggy Frog
Oh, right. But the NSArray retains it, so I could just release _item_ after adding it to the array instead, right?
MathieuK
I did a -1 on this cos what you did allowed you to display it for that one viewcontroller, it does not follow all subsequent view controllers through the life of the navigation ... which is what most toolbars are wont to do.
Jann
Just what I was looking for. @Jann - What if you have different toolbar buttons per View? If you do then this is exactly what you would want, code that dynamically sets the ToolBar Items.
Louis Russell