我想在我的导航栏中添加一个默认的左侧按钮项。当UINavigationController没有提供返回按钮时,它应该显示。
最佳做法是什么?
我想在我的导航栏中添加一个默认的左侧按钮项。当UINavigationController没有提供返回按钮时,它应该显示。
最佳做法是什么?
- (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];
}
以下是添加 leftBarButtonItem
的 Swift 代码:
let leftMenuItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "leftMenuItemSelected:");
self.navigationItem.setLeftBarButtonItem(leftMenuItem, animated: false);
更新
适用于Swift 4及以上版本
let leftMenuItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(leftMenuItemSelected(_:)))
self.navigationItem.setLeftBarButton(leftMenuItem, animated: false);
Swift 3版本:
let done = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(YourController.done))
navigationItem.setLeftBarButtonItem(done, animated: false)
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.")
}