iOS 自定义导航栏返回按钮

原文地址
参考1:关于backBarButtonItem的N种方法
参考2:How to make custom UINavigationController back button image without title

需求

项目中经常需要自定义导航栏返回按钮,只显示文字或者图片

iOS 自定义导航栏返回按钮_第1张图片

只显示图片

分析

自定义导航栏返回按钮的思路很多:

  1. 每个子视图控制器中修改 leftBarButtonItem 的样式,缺点是重复工作量大,如有变更不易修改。
  2. 基类中通过实现 UINavigationController 的代理判断是否是栈底,如果不是栈底,则修改 leftBarButtonItem 的样式。
  3. 在基类中设置backBarButtonItem,易于修改,工作量小。
  4. Method Swizzling:将系统自带的backBarButtonItem方法替换成我们自定义的方法。

实现

方法2:

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    UIViewController *root = navigationController.viewControllers[0];

    if (root != viewController) {
        UIBarButtonItem *itemleft = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backBtn"] style:UIBarButtonItemStylePlain target:self action:@selector(popAction:)];
        viewController.navigationItem.leftBarButtonItem = itemleft;
    }
}


- (void)popAction:(UIBarButtonItem *)barButtonItem
{
    [self.navigationController popViewControllerAnimated:YES];
}

方法3:

     //只显示文字
    //self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];

    //只显示图片
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"nav_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:nil action:nil];

    //更改返回按钮填充颜色
   //self.navigationController.navigationBar.tintColor = [UIColor darkGrayColor];

    //隐藏默认的返回箭头
    self.navigationController.navigationBar.backIndicatorImage = [UIImage new];
    self.navigationController.navigationBar.backIndicatorTransitionMaskImage = [UIImage new];

方法4:

+(void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method originalMethodImp = class_getInstanceMethod(self, @selector(backBarButtonItem));
        Method destMethodImp = class_getInstanceMethod(self, @selector(myCustomBackButton));
        method_exchangeImplementations(originalMethodImp, destMethodImp);
    });
}

static char kCustomBackButtonKey;

-(UIBarButtonItem *)myCustomBackButton{
    UIBarButtonItem *item = [self myCustomBackButton];
    if (item) {
        return item;
    }
    item = objc_getAssociatedObject(self, &kCustomBackButtonKey);
    if (!item) {
        item = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:NULL];
        objc_setAssociatedObject(self, &kCustomBackButtonKey, item, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return item;
}

- (void)dealloc
{
    objc_removeAssociatedObjects(self);
}

你可能感兴趣的:(iOS)