简体   繁体   中英

Add a left bar button item to UINavigationController when no back button is present

I'd like to add a default left bar button item to my navigation bar. It should only display when there is no back button supplied by the UINavigationController.

What is the best approach?

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if(navigationController.viewControllers.count != 1) { // not the root controller - show back button instead
        return;
    }
    UIBarButtonItem *menuItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize
                                                                              target:self
                                                                              action:@selector(menuItemSelected:)];   
    [viewController.navigationItem setLeftBarButtonItem:menuItem]; 
}

Swift code to add leftBarButtonItem

    let leftMenuItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "leftMenuItemSelected:");
    self.navigationItem.setLeftBarButtonItem(leftMenuItem, animated: false);

Update

For Swift 4 & above

    let leftMenuItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(leftMenuItemSelected(_:)))
    self.navigationItem.setLeftBarButton(leftMenuItem, animated: false);

Swift 3 version:

let done = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(YourController.done))
navigationItem.setLeftBarButtonItem(done, animated: false)

For Swift 4.x and later(5.x)

func addNavigationItemBtn(){
    let backBtn = UIBarButtonItem.init(title: "Menu", style: .plain, target: self, action: #selector(menuAction))
    self.navigationItem.leftBarButtonItem = backBtn
}

@objc func menuAction(){
    print("menu button pressed")  //Do your action here
}

Swift 4

let item = UIBarButtonItem(title: "Setting", style: .done, target: self, action: #selector(setting))

 navigationItem.rightBarButtonItem = item

// then do your action in function setting 

@objc
  final func setting() {
    print("Your work here.")
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM