我的ios进阶iOS Developer程序员

如何捕获popViewControllerAnimated方法

2016-03-24  本文已影响1632人  孤獨的守望者

如果使用系统自带的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;
}
上一篇下一篇

猜你喜欢

热点阅读