美文网首页
统一设置导航栏返回按钮

统一设置导航栏返回按钮

作者: 冷洪林 | 来源:发表于2016-10-28 23:23 被阅读168次
    在开发中经常遇到需要统一设置到航条返回按钮的需求,如果在每次都设置一次明显不符合程序员做事风格,也不契合面向对象的封装思想,所以本文主要介绍在自定义导航控制器中,统一设置导航条,接下来介绍步骤:
    • 自定义导航控制器,有没每一个子控制器都需要push为栈顶控制器,所以我们可以拦截导航控制器的push操作,在pus之前设置好导航条的返回按钮:
    - (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];
    }
    
    • 但是这样是不行的,还需要判断当前控制器是否是跟控制器,通过判断当前控制器的子控制器是否大于0,如果大于0,则当前控制器不是跟控制器,此时才能设置返回按钮:
    - (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];
    }
    
    • 在上面的代码中的backItemWitnImage方法是对UIBarButtonItem的类方法进行封装,具体代码如下:
    + (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];
    }
    
    • 到此为止,所有的导航条非根控制器的返回按钮就一次性完成啦

    相关文章

      网友评论

          本文标题:统一设置导航栏返回按钮

          本文链接:https://www.haomeiwen.com/subject/nrseuttx.html