Ser Pounce
Ser Pounce

Reputation: 14527

What is the correct way to add a toolbar to a navigation viewcontroller?

So I'm trying to add a UIToolbar to a UIViewController that is part of a UINavigation hierarchy and I was wondering what is the best way to do this. I know in iOS3 they enabled each viewcontroller that is part of a navigation hierarchy to have it's own toolbar so I figure this is the best way to do it. However, the syntax of how I'm doing is bugging me, as I'm using three different types of syntax to add the toolbar as follows:

[[self navigationController] setToolbarHidden:NO]; 
[self setToolbarItems: myToolbarButtons];
[[[self navigationController] toolbar]setBarStyle:UIBarStyleBlack];

This works fine, and actually fixes a bad memory access from when I was adding the toolbar to the subview of the navigation view. But I don't understand how I can do "self setToolbarItems" after I make the toolbar visible. Does it become a part of the viewcontroller then? Like I said, this works but is bugging me.

Upvotes: 0

Views: 483

Answers (2)

Bittu
Bittu

Reputation: 676

An UIVIewController has a property called UINavigationController. Each UINavigationController has a built-in toolbar of their own. So when you are calling,

[[self navigationController] setToolbarHidden:NO];

you are actually enabling the toolbar of the navigationController property that comes with each UIViewController. And when you set the toolbar's item and style with the following two lines:

[self setToolbarItems: myToolbarButtons];
[[[self navigationController] toolbar]setBarStyle:UIBarStyleBlack];

you are actually setting the items of that UINavigationController's built-in toolbar.

Hope this helps. Check out the UIViewController Class Reference for more information.

Upvotes: 1

fearmint
fearmint

Reputation: 5334

In line 1 you're sending a message to the toolbar's superview to hide it which is done this way because then the superview can do whatever resizing/layout it wants at the best time.

The navigation controller reads the toolbar from self's variables in line 2, because the navigation controller is currently presenting self.

In line 3 you're accessing the toolbar itself, managed by navigationController. This is a part of the toolbar that relates to itself and not the navigation controller, so the navigation controller doesn't expose ways to modify it, allowing you to access the toolbar directly and then modify it.

This way you are accessing the toolbar at various levels making it easier on yourself. For In the first line you don't have to manage displaying it. In the second and third lines you don't have to manage creating/destroying it.

Upvotes: 0

Related Questions