Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding back button to navigation bar

I've added a navigation bar to a UIViewController. It is displayed from another UIViewController only. I'd like to have a left side back button that is shaped similar to an arrow, just like the normal navigation bar back button. It seems I can only add a bar button through IB. I'm guessing the back button needs to be added programmatically. Any suggestions on how I should do this?

Currently, in the RootController, I push another UIViewController (viewB) by simply doing an addSubView. In viewB, I want to display the navigation bar. The app is view based, not navigation controller based.

like image 680
4thSpace Avatar asked May 17 '10 03:05

4thSpace


2 Answers

If you're using a navigation controller:

MyViewController *_myViewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];
[[self navigationController] pushViewController:_myViewController animated:YES];
UIBarButtonItem *_backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleDone target:nil action:nil];
self.navigationItem.backBarButtonItem = _backButton;
[_backButton release], _backButton = nil;
[_myViewController release], _myViewController = nil;

If you're not using a navigation controller, look into the Three20 style components to make custom bar buttons.

like image 148
Alex Reynolds Avatar answered Oct 06 '22 21:10

Alex Reynolds


I have done it the following way

In viewDidLoad Method I have this code:

UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 41)];
    navBar.delegate = self;

    UINavigationItem *backItem = [[UINavigationItem alloc] initWithTitle:@"Back"];
    [navBar pushNavigationItem:backItem animated:NO];
    [backItem release];

    UINavigationItem *topItem = [[UINavigationItem alloc] initWithTitle:@"Your Title"];
    [navBar pushNavigationItem:topItem animated:NO];
    topItem.leftBarButtonItem = nil;
    [topItem release];

    [self.view addSubview:navBar];
    [navBar release];

Then add conformity to UINavigationBarDelegate protocol in the header and implement the delegate method this way:

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
{
    //if you want to dismiss the controller presented, you can do that here or the method btnBackClicked

    return NO;
}
like image 29
Hassan Rasheed Avatar answered Oct 06 '22 21:10

Hassan Rasheed