iOS全屏返回导航控制器最全面实现

github下载链接
用系统的手势加到导航控制器的view上,实现全屏返回,很多人都会,可视项目中有很多特殊需求,
一: 真正的全屏返回,包含导航栏.非系统返回效果.使用要尽可能简单.
二: model出来一个导航控制器,我想侧滑时候到根控制器时候,侧滑就 dissmiss掉.
三: 可以禁止单个控制器里的侧滑手势.
四: 返回按钮写在导航控制器里,我想取到点击返回按钮时候调动的方法.可以临时禁止侧滑.
无: 如果控制器里面有横向很长的scrollView,侧滑手势失效,我要处理这个.

#import <UIKit/UIKit.h>

@interface QDNavigationController : UINavigationController

//present出来的根控制器,右滑dissmiss 默认关闭 NO
@property (nonatomic, assign) BOOL needDissMiss;

/* 子控制器写下面的方法 可以关闭全屏返回
 reture NO 关闭当前页面全屏返回效果  默认开启全屏返回
 - (BOOL)QDNavigationControllerEnabled{
    return NO;
 }
 
 控制器将要pop或 dismiss时候调用  return NO 取消销毁页面,正常销毁页面 return YES;
 - (BOOL)QDNavigationControllerWillGoBack{
    return YES;
 }

 目前直接放在控制器View上的scrollView都能自动实现滑动到最左边再手势返回,如果scrollView层级比较深,或者特殊情况下才允许手势返回如(需要手势在页面左侧滑动范围内才生效),需要实现下面方法,return YES后才能手势返回
- (BOOL)QDNavigationControllerAllowDragBack:(UIGestureRecognizer *)gestureRecognizer{
    return YES;

}
 
 */


@end



#import "QDNavigationController.h"

@interface QDNavigationController ()<UIGestureRecognizerDelegate>
{
    //开始点击的位置
    CGPoint startTouch;
    //上一个控制器截图
    UIImageView *lastScreenShotView;
    //返回时页面蒙版
    UIView *blackMask;
}

//背景view
@property (nonatomic,strong) UIView *backgroundView;
//截屏图片数组
@property (nonatomic,strong) NSMutableArray *screenShotsList;
//是否动画中
@property (nonatomic,assign) BOOL isMoving;
//拖拽手势
@property (weak, nonatomic) UIPanGestureRecognizer *pan;

@end

@implementation QDNavigationController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.screenShotsList = [NSMutableArray new];
        self.needDissMiss = NO;
    }
    return self;
}

- (void)dealloc{
    self.screenShotsList = nil;
    [self.backgroundView removeFromSuperview];
    self.backgroundView = nil;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //navigationBar 样式
    self.navigationBar.translucent = NO;
    self.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationBar.backgroundColor = [UIColor whiteColor];
    //去掉原来的边缘侧滑手势
    self.interactivePopGestureRecognizer.enabled = NO;
    
    self.view.backgroundColor = [UIColor whiteColor];
    //拖拽手势
    UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self
                                                                                   action:@selector(paningGestureReceive:)];
    [panRecognizer delaysTouchesBegan];
    [self.view addGestureRecognizer:panRecognizer];
    panRecognizer.delegate = self;
    self.pan = panRecognizer;
}


#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    // 两个Pan手势不能同时触发
    if ([otherGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]) {
        return YES;
    } else {
        return NO;
    }
}

//允许多个手势同时响应
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

//手势是否响应
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    //是否是pan手势
    BOOL isPanGesture = ([self.pan isEqual:gestureRecognizer]);
    if (!isPanGesture) {//非self.pan 拖拽手势,不特殊处理
        return YES;
    }
    CGPoint point = [self.pan velocityInView:self.pan.view];

    // 如果是向左滑动,或者y轴的分量过大,那么不启用效果
    if ((point.x < 0 || fabs(point.y) > fabs(point.x) / 2)) {
        return NO;
    }
    
    UIViewController *viewController = [self.viewControllers lastObject];
    // -Wundeclared-selector忽略performSelector导致的警告
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
    
    //如果子控制器里实现关闭侧滑手势方法return NO. 手势不生效.
    if ([viewController respondsToSelector:@selector(QDNavigationControllerEnabled)]) {
        if ([viewController performSelector:@selector(QDNavigationControllerEnabled)] == NO) {
            return NO;
        }
    }
    
    //一定区域内可以滑动,或者webView等scrollView层级比较深的页面,实现QDNavigationControllerAllowDragBack
    if ([viewController respondsToSelector:@selector(QDNavigationControllerAllowDragBack:)]) {
        if ([viewController performSelector:@selector(QDNavigationControllerAllowDragBack:) withObject:gestureRecognizer] == NO) {
            return NO;
        }else{
            return YES;
        }
    }
    
    
    //滑动时候,向右滑动在横向滑动的scrollView的话,滑动到scrollView的contentSize的x == 0时,(最左边)才能触发侧滑手势
    //有符合条件的ScrollView 特殊处理
    BOOL hasScroll = NO;
    //是否可以全屏返回
    BOOL needPop = NO;
    //触摸点
    CGPoint pointNow = [gestureRecognizer locationInView:self.view];
    
    for (UIView *subVi in [self.viewControllers lastObject].view.subviews) {
        //这个scrollview包含这点 往右滑 contentSize宽度大于屏幕宽度 在最左边时候 系统手势被屏蔽 手动pop
        if ([subVi isKindOfClass:NSClassFromString(@"UIScrollView")]
            && ((UIScrollView *)subVi).contentSize.width > kScreenWidth
            ){
            hasScroll = YES;
            //scrollView的ContentSize 转成frame判断触摸点是否在scrollView上
            CGSize scrollContentSize = ((UIScrollView *)subVi).contentSize;
            CGRect contentSizeRect = CGRectMake(0, 0, scrollContentSize.width, scrollContentSize.height);
            //scrollView在最左边 触摸点在scrollView上 可以全屏返回
            if ( ((UIScrollView *)subVi).contentOffset.x <= 0
                && CGRectContainsPoint( contentSizeRect, [self.view convertPoint:pointNow toView:subVi])
                ){
                needPop = YES;
                break;
            }
            //触摸点不在scrollView上 可以全屏返回
            if (hasScroll == YES && !CGRectContainsPoint( contentSizeRect, [self.view convertPoint:pointNow toView:subVi])) {
                needPop = YES;
                break;
            }
        }
        
    }
    
    //不是跟控制器,符合可以侧滑条件
    if (self.viewControllers.count > 1 && (hasScroll == NO || needPop == YES)) {
        if ([self needGoback] == NO) {
            return  NO;
        }else{
            return YES;
        }
    }else{
        if (self.viewControllers.count == 1
            && (hasScroll == NO || needPop == YES)
            && [self.pan translationInView:[self.viewControllers lastObject].view].x > 2) {
            //根控制器 符合条件 dismiss
            [self popOrDissMiss];
        }
        return NO;
    }
    
}


- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
    
    if (self.viewControllers.count >= 1 ) {
        viewController.hidesBottomBarWhenPushed = YES;
        //子控制器创建返回按钮
        viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[self creatBackButton]];
        
        //截图
        UIImage *capture = [self _captureForNavigationController:self];
        
        // 有时会获得nil,为防止crash使用[NSNull null]放入数组
        if (capture) {
            [self.screenShotsList addObject:capture];
        } else {
            [self.screenShotsList addObject:[NSNull null]];
        }
    }
    
    [super pushViewController:viewController animated:animated];
}

- (UIViewController *)popViewControllerAnimated:(BOOL)animated{
    [self.screenShotsList removeLastObject];
    
    return [super popViewControllerAnimated:animated];
}

//截图
- (UIImage *)_captureForNavigationController:(UINavigationController *)navigationController
{
    UIView *view = navigationController.view;
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, view.window.screen.scale);
    
    /* iOS 7 */
    if ([view respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
        [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
    else /* iOS 5,6 */
        [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage* ret = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return ret;
}

//返回方法
- (void)popOrDissMiss{
    if ([self needGoback] == NO) {
        return ;
    }
    if (self.viewControllers.count == 1 && self.needDissMiss == YES) {
        [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    [self popViewControllerAnimated:YES];
}

//如果子控制器实现 QDNavigationControllerWillGoBack方法
- (BOOL)needGoback{
    UIViewController *viewController = [self.viewControllers lastObject];
    //控制器里面实现QDNavigationControllerWillGoBack方法 并return NO可以取消销毁页面
    if ([viewController respondsToSelector:@selector(QDNavigationControllerWillGoBack)]) {
        if ([viewController performSelector:@selector(QDNavigationControllerWillGoBack)] == NO) {
            return NO;
        }
    }
    return YES;
}
#pragma clang diagnostic pop

//拖拽手势执行
- (void)paningGestureReceive:(UIPanGestureRecognizer *)recoginzer
{
    if (self.screenShotsList.count <= 0) return;
    UIViewController *currentViewController = [self.viewControllers lastObject];
    
    CGPoint touchPoint = [recoginzer locationInView: [[UIApplication sharedApplication] keyWindow]];
    
    if (recoginzer.state == UIGestureRecognizerStateBegan) {
        
        _isMoving = YES;
        startTouch = touchPoint;
        
        if (!self.backgroundView)
        {
            CGRect frame = self.view.frame;
            
            self.backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width , frame.size.height)];
            [self.view.superview insertSubview:self.backgroundView belowSubview:self.view];
            
            blackMask = [[UIView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width , frame.size.height)];
            blackMask.backgroundColor = [UIColor blackColor];
            [self.backgroundView addSubview:blackMask];
        }
        
        self.backgroundView.hidden = NO;
        
        if (lastScreenShotView) [lastScreenShotView removeFromSuperview];
        
        id lastScreenShotObject = [self.screenShotsList lastObject];
        UIImage *lastScreenShot;
        if (lastScreenShotObject == [NSNull null]) {
            lastScreenShot = nil;
        } else {
            lastScreenShot = lastScreenShotObject;
        }
        
        lastScreenShotView = [[UIImageView alloc]initWithImage:lastScreenShot];
        
        [lastScreenShotView setFrame:CGRectMake(0,
                                                lastScreenShotView.frame.origin.y,
                                                lastScreenShotView.frame.size.height,
                                                lastScreenShotView.frame.size.width)];
        
        [self.backgroundView insertSubview:lastScreenShotView belowSubview:blackMask];
        
        currentViewController.view.userInteractionEnabled = NO;
        currentViewController.view.layer.rasterizationScale = [[UIScreen mainScreen] scale];
        currentViewController.view.layer.shouldRasterize = YES;
    }else if (recoginzer.state == UIGestureRecognizerStateEnded){
        //销毁
        if (touchPoint.x - startTouch.x > 80)
        {
            [UIView animateWithDuration:0.2 animations:^{
                //适配大屏幕,同时解决了pop不能到屏幕最右边的现象和pop后 邮件列表 和 会话 toolbar重影的问题
                [self moveViewWithX:self.view.bounds.size.width];
            } completion:^(BOOL finished) {
                if (self.viewControllers.count > 1) {
                    [self popViewControllerAnimated:NO];
                }
                
                CGRect frame = self.view.frame;
                frame.origin.x = 0;
                self.view.frame = frame;
                
                _isMoving = NO;
            }];
        }
        else
        {//不销毁返回
            [UIView animateWithDuration:0.3 animations:^{
                [self moveViewWithX:0];
            } completion:^(BOOL finished) {
                _isMoving = NO;
                self.backgroundView.hidden = YES;
                currentViewController.view.userInteractionEnabled = YES;
                currentViewController.view.layer.shouldRasterize = NO;
            }];
            
        }
        return;
        
    }else if (recoginzer.state == UIGestureRecognizerStateCancelled){
        
        [UIView animateWithDuration:0.3 animations:^{
            [self moveViewWithX:0];
        } completion:^(BOOL finished) {
            _isMoving = NO;
            self.backgroundView.hidden = YES;
            currentViewController.view.layer.shouldRasterize = NO;
        }];
        
        return;
    }
    
    if (_isMoving) {
        [self moveViewWithX:touchPoint.x - startTouch.x];
    }
}

//开始移动
- (void)moveViewWithX:(float)x
{
    //x < 0时,view已经移动到了最左边了,不需要执行任何操作了
    if (x < 0) {
        return;
    }
    
    CGRect frame = self.view.frame;
    frame.origin.x = x;
    self.view.frame = frame;
    
    float alpha = 0.4 - (x/800);
    
    blackMask.alpha = alpha;
    
    // 直接将照片贴着屏幕底边展示即可
    id lastScreenShotObject = [self.screenShotsList lastObject];
    UIImage *lastScreenShot;
    if (lastScreenShotObject == [NSNull null]) {
        lastScreenShot = nil;
    } else {
        lastScreenShot = lastScreenShotObject;
    }
    
    CGFloat lastScreenShotViewHeight = lastScreenShot.size.height;
    CGFloat superviewHeight = lastScreenShotView.superview.frame.size.height;
    CGFloat y = superviewHeight - lastScreenShotViewHeight;
    
    CGFloat gapScale = 0.04 * (kScreenWidth - x) / kScreenWidth; //间隙 0
    
    [lastScreenShotView setFrame:CGRectMake(gapScale * kScreenWidth,
                                            y + gapScale * lastScreenShotViewHeight,
                                            (1 - 2 * gapScale) * kScreenWidth,
                                            (1 - 2 * gapScale) * lastScreenShotViewHeight)];
    
}

//返回按钮
- (UIButton *)creatBackButton{
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 24.0f, 44.0f)];
    [backButton setImage:[UIImage imageNamed:@"daylight-btn-left-arrow-normal"] forState:UIControlStateNormal];
    [backButton setImage:[UIImage imageNamed:@"daylight-btn-left-arrow-highlighted"] forState:UIControlStateHighlighted];
    [backButton addTarget:self action:@selector(popOrDissMiss) forControlEvents:UIControlEventTouchUpInside];
    return backButton;
}

@end




最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,921评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,635评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,393评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,836评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,833评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,685评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,043评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,694评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,671评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,670评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,779评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,424评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,027评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,984评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,214评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,108评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,517评论 2 343

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,019评论 4 62
  • 因为我们太少得到我们想要的东西,即使得到,我们也怕失去。或许这就是一种病。 如果要给这个病加一个定义,它叫做"幸福...
    蝈蝈大叔阅读 847评论 0 2
  • 今天是大年三十除夕之夜,一大早打开手机便收到很多朋友的祝福信息,还收到姐姐的压岁红包,真是美好一天的开始呢! ...
    是你路过我的倾城时光0614阅读 214评论 0 0
  • 抓丁义珍的时候,季昌明检察长坚持向达康书记做报告,这里有三个关键人物出场了,一个是省委副书记高育良,一个是新来的省...
    淇畔芷影阅读 581评论 0 3
  • 我不曾记得,于岁月的流纹中,我曾遇见你 我也终将忘却,一面夏至的湖泊,波澜永不兴 一场繁星的眼泪把夜空灌醉 一片变...
    刺猬小姐木果果阅读 367评论 0 5