views:

67

answers:

1

I have buttons in my navigation bar and in a toolbar subview of a container view whose enabled property depends on app state. Currently the buttons are set in viewWillAppear, so the right thing happens if I navigate away from the view then return. I thought [containerView setNeedsDisplay] would do the trick, but no.

(I have UITextViews in the container view that I can force to update when textView.text is changed, but the app logic is such that it is harder to explicitly update all of the correct buttons as the state changes.)

A: 


You can change the state of navigationBar and toolbar buttons anywhere in your code. For initial setup of the view, it's useful to put some code in the viewWillDisappear and viewWillAppear, as you have done.

For example, if you wanted to programatically change a button on the navigationBar from 'Cancel' to 'Enter' when you've added some text to your textField you can just initialise a new UIBarButtonItem and stick it where the old one was. Say you added the 'Cancel' button in your viewWillAppear like so...

- (void)viewWillAppear:(BOOL)animated {
self.navigationItem.rightBarButtonItem = 
[[[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStylePlain target:self action:@selector(cancelAction)] autorelease];
}

then elsewhere in your code you can simply overwrite that navigation item by making a new one in exactly the same way. However, you're clearly going to want to give it a different title ('Enter' in my example here) and perhaps a different action.


In terms of the toolbar, UINavigationControllers can easily handle changes. This is because every UINavigationController+UIViewController combo come with a built in toolbar, it's just that they don't display it unless you specifically request that. The best method to do so is to set the toolbar items for the UIViewController and then ask the navigationController to display/hide the toolbar as required.

So, for example, say I make three UIBarButtonItem instances in the initialisation method of the UIViewController... then all I need to do is stick them in an array and assign that array of items to the toolbar, e.g.

[self setToolbarItems:[NSArray arrayWithObjects:button1, button2, button3, nil] animated:NO];

then in the viewWillAppear (or viewDidAppear) methods I can use the navigationController to display the toolbar:

[self.navigationController setToolbarHidden:NO animated:YES];

Just remember to do the opposite when the view will go away (i.e. the same call but with setToolbarHidden:YES). At any point in the code for your UIViewController, you can change the buttons using the same approach as you did in the initialisation, i.e. [self setToolbarItems:.....].

imnk
Looks promising... I'll update again when I've had a chance to try this out!
iPhoneDollaraire