统一设置导航栏返回按钮

2016-10-28  本文已影响168人  冷洪林
在开发中经常遇到需要统一设置到航条返回按钮的需求,如果在每次都设置一次明显不符合程序员做事风格,也不契合面向对象的封装思想,所以本文主要介绍在自定义导航控制器中,统一设置导航条,接下来介绍步骤:
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{

    UIBarButtonItem *item = [UIBarButtonItem backItemWitnImage:[UIImage imageNamed:@"navigationButtonReturn"] selectImage:[UIImage imageNamed:@"navigationButtonReturnClick"] target:self action:@selector(back) title:@"返回"];
    viewController.navigationItem.leftBarButtonItem = item;
    [super pushViewController:viewController animated:animated];
}
- (void)back
{
    [self popViewControllerAnimated:YES];
}
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
    
    if (self.childViewControllers.count > 0) { // 非根控制器
        UIBarButtonItem *item = [UIBarButtonItem backItemWitnImage:[UIImage imageNamed:@"navigationButtonReturn"] selectImage:[UIImage imageNamed:@"navigationButtonReturnClick"] target:self action:@selector(back) title:@"返回"];
        viewController.navigationItem.leftBarButtonItem = item;
    }
    
    [super pushViewController:viewController animated:animated];
    
}
- (void)back
{
    [self popViewControllerAnimated:YES];
}
+ (UIBarButtonItem *)backItemWitnImage:(UIImage *)aImage selectImage:(UIImage *)aSelectImage target:(id)aTarget action:(SEL)aAction title:(NSString *)aTitle
{
    UIButton *btn = [[UIButton alloc] init];
    [btn setImage:aImage forState:UIControlStateNormal];
    [btn setImage:aSelectImage forState:UIControlStateHighlighted];
    [btn setTitle:aTitle forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    btn.contentEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    [btn sizeToFit];
    [btn addTarget:aTarget action:aAction forControlEvents:UIControlEventTouchUpInside];
    UIView *containerView = [[UIView alloc] initWithFrame:btn.bounds];
    [containerView addSubview:btn];
    return [[UIBarButtonItem alloc] initWithCustomView:containerView];
}

上一篇下一篇

猜你喜欢

热点阅读