程序员

UIViewController+BackButtonHandl

2019-01-11  本文已影响11人  鄂北

UIViewController+BackButtonHandler是用来拦截系统导航栏返回事件,并提供方法来处理返回事件

UIViewController+BackButtonHandler.h

#import <UIKit/UIKit.h>

@protocol BackButtonHandlerProtocol <NSObject>
@optional
// 重写下面的方法以拦截导航栏返回按钮点击事件,返回 YES 则 pop,NO 则不 pop
-(BOOL)navigationShouldPopOnBackButton;
@end

// 表示遵循这个代理
@interface UIViewController (BackButtonHandler) <BackButtonHandlerProtocol>

@end

UIViewController+BackButtonHandler.h是UIViewController的分类,在.h里声明一个代理方法

UIViewController+BackButtonHandler.m

#import "UIViewController+BackButtonHandler.h"

@implementation UIViewController (BackButtonHandler)

@end

@implementation UINavigationController (ShouldPopOnBackButton)//UINavigationController的分类

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
    //判断是否返回
    if([self.viewControllers count] < [navigationBar.items count]) {
        return YES;
    }
    
    BOOL shouldPop = YES;
    //获取最上层的UIViewController
    UIViewController* vc = [self topViewController];
    //判断是否有navigationShouldPopOnBackButton方法
    if([vc respondsToSelector:@selector(navigationShouldPopOnBackButton)]) {
        shouldPop = [vc navigationShouldPopOnBackButton];
    }
    
    if(shouldPop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self popViewControllerAnimated:YES];
        });
    } else {
        // 取消 pop 后,复原返回按钮的状态
        for(UIView *subview in [navigationBar subviews]) {
            if(0. < subview.alpha && subview.alpha < 1.) {
                [UIView animateWithDuration:.25 animations:^{
                    subview.alpha = 1.;
                }];
            }
        }
    }
    return NO;
}

@end

respondsToSelector方法是用来判断是否有以某个名字命名的方法

上一篇下一篇

猜你喜欢

热点阅读