如何捕获popViewControllerAnimated方法

如果使用系统自带的leftBarButtonItem来处理的话,就需要使用自定义图片,这种方法使用起来并不友好,正好在简书上看到了一位兄弟发出来的解决方案,这里把代码贴一下,有助于大家直观的理解,项目地址:

https://github.com/XinStar1/AZXTallyBook

整体的思路就是使用新建一个Category用来拦截popViewControllerAnimated的方法,话不多说,直接上代码

UIViewController+BackButtonHandler.h

#import <UIKit/UIKit.h>

@protocol BackButtonHandlerProtocol <NSObject>

@optional

// Override this method in UIViewController derived class to handle 'Back' button click

-(BOOL)navigationShouldPopOnBackButton;

@end

@interface UIViewController (BackButtonHandler) <BackButtonHandlerProtocol>

@end

UIViewController+BackButtonHandler.m

#import "UIViewController+BackButtonHandler.h"

@implementation UIViewController (BackButtonHandler)

@end

@implementation UINavigationController (ShouldPopOnBackButton)

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
    
    if([self.viewControllers count] < [navigationBar.items count]) {
        return YES;
    }
    
    BOOL shouldPop = YES;
    UIViewController* vc = [self topViewController];
    if([vc respondsToSelector:@selector(navigationShouldPopOnBackButton)]) {
        shouldPop = [vc navigationShouldPopOnBackButton];
    }
    
    if(shouldPop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self popViewControllerAnimated:YES];
        });
    } else {
        // Workaround for iOS7.1. Thanks to @boliva - http://stackoverflow.com/posts/comments/34452906
        for(UIView *subview in [navigationBar subviews]) {
            if(0. < subview.alpha && subview.alpha < 1.) {
                [UIView animateWithDuration:.25 animations:^{
                    subview.alpha = 1.;
                }];
            }
        }
    }
    
    return NO;
}

@end

调用方式如下

-(BOOL) navigationShouldPopOnBackButton
{
    //其他的可执行方法
    return YES;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,219评论 30 472
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,705评论 25 709
  • 前言 由于最近两个多月,笔者正和小伙伴们忙于对公司新项目的开发,笔者主要负责项目整体架构的搭建以及功能模块的分工。...
    CoderMikeHe阅读 27,173评论 74 270
  • 新上映的电影还没有看,听说是这俩人招募了正义联盟的成员🧐
    Hi_木阅读 169评论 0 2
  • 学习的主动性不高。主要体现在一下几个方面。 1.虽然知道输出倒逼输入,每天都写东西,但有时不是每天都学习输入,有时...
    孤狼龙浩阅读 756评论 0 0