What is the proper way to access navbar buttons of a modal view?

251 views Asked by At

I created a view in IB with a navbar and a table. On the navbar I put two buttons, cancel and done. I use this view like a modal view with:

[self presentModalViewController:controller animated:YES];

My problem is when I use:

[self.navigationItem.rightBarButtonItem setEnabled:YES];

to enable the right button. It doesn't work.

Have I to set a delegate? what code passages I have to do? It works if I create an IBOutlet for the right button and I use [doneButton setEnabled:YES], but I think this isn't the proper way.

2

There are 2 answers

2
zrzka On BEST ANSWER

Delegate has nothing to do with your issue.

You probably did put navigation bar into your view directly. Thus things like self.navigationItem doesn't work. You have two choices ...

Connect your buttons to outlets in your code and access them directly.

Or remove navigation bar from your view and present your view controller in this way ...

MyViewController *vc = [[MyViewController alloc] initWith...];
UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:vc];
[vc release];
[self presentModalViewController:navCon animated:YES];
[navCon release];

... and now you can access left/right buttons via navigationItem.

0
Bogatyr On

In order to place a navigation bar on your modal view controller in interface builder (and set up bar button items that call actions in your detail view controller), you need to go through a level of indirection (your navigation bar will be in one .xib, and the details of your detail view will be in a different xib):

  • create a xib file containing a navigation controller object, and set its root view controller to be your detail view controller that you want to display modally with a navigation bar.

  • add bar button items to the detail controller's navigation bar and hook them up to IBActions in your detail view controller object.

  • your detail view controller will need to be in a separate .xib file

  • create a "loader" object that just exists to hold the navigation controller iboutlet, and set it to be the File's Owner object of that xib:

@interface Loader : NSObject
@property (nonatomic, retain) IBOutlet UINavigationController *navVC;
@end

@implementation Loader
@synthesize navVC;
- (void) dealloc
{
    [navVC release];
    [super dealloc];
}
@end

Your xib file containing the navigation controller will look like this:

enter image description here

Make sure the navigation controller object is conntected to the "Loader" object's navVC outlet, and make sure the bar button items are connected to your detail view controller's desired IBActions.

Then you present this whole thing using this code:

Loader *loader = [[[Loader alloc] init] autorelease];
[[NSBundle mainBundle] loadNibNamed:@"ModalVC" owner:loader options:nil];
[self presentModalViewController:loader.navVC animated:YES];