"self.navigationItem.rightBarButtonItem" Not working
I have the following code taken straight from the NavBar sample code from Apple. I put this in the viewDidLoad method for a view in my app that is being presented modally, and it wont work.
UIBarButtonItem *addButton = [[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"AddTitle", @"")
开发者_如何学C style:UIBarButtonItemStyleBordered
target:self
action:@selector(addAction:)] autorelease];
self.navigationItem.rightBarButtonItem = addButton;
Any Suggestions?
Okay explained solution:
presentModalViewController:animated: presents a viewController modally, which does not have a UINavigationBar
, so you can do some things:
- Add a
UINavigationBar
in your viewController's nib and add the "Add" button there and everything you need to setup. - You can use
pushViewController:animated
: to show the viewController modally which will be on the navigation stack and have theUINavigationBar
for you to add your button - If your first viewController is not a
UINavigationController
, usingpushViewController:animated:
won't solve it, so you can present aUINavigationController
modally with your viewController as the rootViewController:
YourViewController *viewController =[[[YourViewController alloc] initWithNibName:@"YourViewController" bundle:nil] autorelease];
UINavigationController *navController = [[[UINavigationController alloc] initWithRootViewController:viewController] autorelease];
[self.navigationController presentModalViewController:navController animated:YES];
Hope any of this helps
You need to use these lines of code on the page where you present the other view.
sceondController *obj=[[[sceondController alloc] initWithNibName:@"sceondController" bundle:nil] autorelease];
UINavigationController *navController=[[[UINavigationController alloc] initWithRootViewController:obj] autorelease];
[self.navigationController presentModalViewController:navController animated:NO];
and in second view use same code which you are using for making navigation button.
May be it resolves your problem.
I assume your view controller is actually a UINavigationController and everything else is in place. In which case I would change two things.
I wouldn't autorelease the UIBarButtonItem. That tends to be unreliable with view controllers so add the button to your list of things to dealloc at cleanup
I would use the setter function to set the button. Here is my code that works in my navigation controller
clearAllButton = [[UIBarButtonItem alloc] initWithTitle:@"Clear All" style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonPressed:)];
[[self navigationItem] setRightBarButtonItem:clearAllButton];
Run your app in real device. In iOS6 it is not working on simulator.
精彩评论