方法一 : 在 NavigationController 中, 重寫父類的push方法
/**
* 攔截所有push進來的子控制器
* @param viewController 每一次push進來的子控制器
*/
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
// if (不是第一個push進來的子控制器) {
if (self.childViewControllers.count >= 1) {
// 左上角的返回
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton setTitle:@"返回" forState:UIControlStateNormal];
[backButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[backButton setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
[backButton setImage:[UIImage imageNamed:@"navigationButtonReturn"] forState:UIControlStateNormal];
[backButton setImage:[UIImage imageNamed:@"navigationButtonReturnClick"] forState:UIControlStateHighlighted];
[backButton sizeToFit];
[backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
backButton.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
viewController.hidesBottomBarWhenPushed = YES; // 隱藏底部的工具條
}
// super的push方法一定要寫到最后面
// 一旦調(diào)用super的pushViewController方法,就會創(chuàng)建子控制器viewController的view
// 也就會調(diào)用viewController的viewDidLoad方法
[super pushViewController:viewController animated:animated];
}
- (void)back
{
[self popViewControllerAnimated:YES];
}
方法二 : 在BaseViewController 中, 寫一個 - (void)setupNavigationwithTitle:(NSString *)title;
方法, 然后, 在需要 "返回" 按鈕的頁面, 調(diào)用此方法.
/**
* 設(shè)置navigationbar的title(同時還默認的包含有設(shè)置返回按鈕為黑色)
*
* @param title title的內(nèi)容
*/
- (void)setupNavigationwithTitle:(NSString *)title;
- (void)setupNavigationwithTitle:(NSString *)title {
UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
backBtn.frame = CGRectMake(0.0, 0.0, 80.0, 40.0);
UIImageView *backImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"back_black"]];
backImg.frame = CGRectMake(-14.0, 2.0, 30.0, 40.0);
[backBtn addSubview:backImg];
UILabel *backLabel = [[UILabel alloc]init];
backLabel.text = @"返回";
backLabel.textColor = [UIColor whiteColor];
backLabel.font = [UIFont systemFontWithSize:16.0f];
backLabel.frame = CGRectMake(10, 2.0, 40, 40);
[backBtn addSubview:backLabel];
[backBtn addTarget:self
action:@selector(btnItemClick)
forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
[self.navigationItem setLeftBarButtonItem:leftButton];
self.title = title;
}
- (void)btnItemClick
{
[self.navigationController popViewControllerAnimated:YES];
}