Adding back button to navigation bar

▼魔方 西西 提交于 2019-11-27 14:08:06

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.

Hassan Rasheed

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;
}

Another approach to solve this problem is to set the items property for the navigation bar instead of consecutively pushing the bar items into nav bar stack:

//Define myFrame based on your needs
let navigationBar = UINavigationBar(frame: myFrame)
let backItem = UINavigationItem(title: "Back")
let topItem = UINavigationItem(title: "My Title")
navigationBar.setItems([backItem,topItem], animated: false)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!