Here is my code. I want to put a back button on the opening rootviewController.
- (void)selectSurah:(id)sender {
SurahTableViewController * surahTableVi
Appearance and behavior of a back button in a UINavigationController relies on interaction between a stack of UINavigationControllers. Putting a back button on the first controller breaks this convention, there's nothing to go back to, which is why your code isn't working.
You'll need to manually add UIBarButtonItem to the title bar code like:
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(back:)];
If you truly want it to look like a back button, you'll need to manually create the UIBarButtonItem with an image that mirrors the back button.
Another suggestion though, as it looks like you are attempting to use a back button to dismiss a modal view controller, I'd stick with something more conventional like a "Close" or "Done" button to close the modal view controller. A back button is really more appropriate for navigating a stack of UINavigationControllers.
Faizan,
Helium3 comment makes sense.
I suppose that your button is needed to dismiss the controller presented modally, is it true? Correct if I'm wrong.
If so, you could just create a new UIBarButtonItem
and set is a left (or right) button for the UINavigationController
navigationItem
. To not break encapsulation create it in the viewDidLoad
method for your SurahTableViewController
controller.
- (void)viewDidLoad
{
[super viewDidLoad];
// make attention to memory leak if you don't use ARC!!!
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Close"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(close:)];
}
-(void)close:(id)sender
{
// to dismiss use dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion
// dismissModalViewControllerAnimated: is deprecated
[self dismissViewControllerAnimated:YES completion:^{ NSLog(@"controller dismissed"); }];
}
I don't believe it's possible to pop the root view controller off the navigation stack, but you can fake it with a UIButton
added as the custom view of a UIBarButtonItem
:
UIButton *b = [[UIButton alloc]initWithButtonType:UIButtonTypeCustom];
[b setImage:[UIImage imageNamed:@"BackImage.png"] forState:UIControlStateNormal];
[b addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
self.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:b];
A suitable PSD of iOS UI elements can be found here.
Since the SurahTableViewController
is a root view controller in a navigation controller you can't go back to the root because you're already there. Since you've presented it modally from something else, you need to put a button on the nav bar that has an IBAction
which calls:
[self dismissModalViewControllerAnimated:YES];