iOS使用系统的导航栏,自定义滑动返回手势与转场(过场)动画

其实,上天给了我十万条理由让我去使用系统的导航栏,然而,仅仅只因为一条,我不得不放弃,我们坑爹的产品经理不喜欢。。。
于是,我走上了一条自定义导航栏(花样作死)的不归路。。。

一、自定义滑动返回手势与滑动动画

代码有点多,为了大家能看懂,我全放在这里,相信同学们看完都能自己写出来,建议去github下个demo,

下载地址:https://github.com/wangzhaomeng/LLNavigationController.git

我实现了个简单的动画效果,如下图:

IMG_0197.PNG

首先说一下思路:

  1. 重写push方法,在每一次push的时候,对当前屏幕进行截图,保存到一个数组中
  2. 重写pop的一系列方法,在每一次pop的时候,移除数组中相对应的截图
  3. 自定义返回手势,滑动的时候,将数组中的最后一张图片,添加到当前视图的下方,产生了上一个视图在当前视图下方的错觉
    思路很简单,不过实现起来,还需要些技巧

下面上代码:
1、首先,创建一个简单的蒙版
#import <UIKit/UIKit.h>
@interface LLScreenShotView : UIView
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIView *maskView;
@end

#import "LLScreenShotView.h"
#define SCREEN_BOUNDS  [UIScreen mainScreen].bounds
@implementation LLScreenShotView
- (id)init{
self = [super initWithFrame:SCREEN_BOUNDS];
if (self) {
    _imageView = [[UIImageView alloc] initWithFrame:SCREEN_BOUNDS];
    [self addSubview:_imageView];
    
    _maskView = [[UIView alloc] initWithFrame:SCREEN_BOUNDS];
    _maskView.backgroundColor = [UIColor blackColor];
    [self addSubview:_maskView];
}
return self;
}
@end

2、创建UINavigationController的子类
#import <UIKit/UIKit.h>
#import "UINavigationController+LLAddPart.h"
@interface LLBaseNavigationController : UINavigationController
@end

#import "LLBaseNavigationController.h"
#import "LLNavControllerDelegate.h"
#import "AppDelegate.h"
@interface LLBaseNavigationController ()<UIGestureRecognizerDelegate>
@property (nonatomic, strong) NSMutableArray<UIImage *> *childVCImages; //保存截屏的数组
@property (nonatomic, strong) LLNavControllerDelegate   *transitionDelagate;
@end

@implementation LLBaseNavigationController
- (void)loadView{
[super loadView];
//self.interactivePopGestureRecognizer.delegate = self; //系统的返回手势代理
self.interactivePopGestureRecognizer.enabled = NO;      //屏蔽系统的返回手势
self.transitionDelagate = [[LLNavControllerDelegate alloc] init];
self.transitionDelagate.presentTransition = @"LLPresentAnimation"; //自定义push动画
self.transitionDelagate.dismissTransition = @"LLDismissAnimation"; //自定义pop动画
self.delegate = self.transitionDelagate;
}

- (void)viewDidLoad{
[super viewDidLoad];
UIPanGestureRecognizer *popRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragging:)];
popRecognizer.delegate = self;
[self.view addGestureRecognizer:popRecognizer];         //自定义的滑动返回手势
self.popRecognizerEnable = YES;                         //默认相应自定义的滑动返回手势
}

#pragma mark - 重写父类方法
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
if (self.childViewControllers.count > 0) {
    [self createScreenShot];
}
[super pushViewController:viewController animated:animated];
}

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

- (NSArray<UIViewController *> *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated{
NSArray *viewControllers = [super popToViewController:viewController animated:animated];
if (self.childVCImages.count >= viewControllers.count){
    for (int i = 0; i < viewControllers.count; i++) {
        [self.childVCImages removeLastObject];
    }
}
return viewControllers;
}

- (NSArray<UIViewController *> *)popToRootViewControllerAnimated:(BOOL)animated{
[self.childVCImages removeAllObjects];
return [super popToRootViewControllerAnimated:animated];
}

- (void)dragging:(UIPanGestureRecognizer *)recognizer{
//如果只有1个子控制器,停止拖拽
if (self.viewControllers.count <= 1) return;
//在x方向上移动的距离
CGFloat tx = [recognizer translationInView:self.view].x;
//在x方向上移动的距离除以屏幕的宽度
CGFloat width_scale;
if (recognizer.state == UIGestureRecognizerStateBegan) {
    //添加截图到最后面
    width_scale = 0;
    [AppDelegate shareDelegete].screenShotView.hidden = NO;
    [AppDelegate shareDelegete].screenShotView.maskView.alpha = 0.5;
    [AppDelegate shareDelegete].screenShotView.imageView.image = [self.childVCImages lastObject];
}
else if (recognizer.state == UIGestureRecognizerStateChanged){
    //移动view
    if (tx>10) {
        width_scale = (tx-10)/self.view.bounds.size.width;
        self.view.transform = CGAffineTransformMakeTranslation(tx-10, 0);
        [AppDelegate shareDelegete].screenShotView.maskView.alpha = 0.5-width_scale*0.5;
    }
}
else if (recognizer.state == UIGestureRecognizerStateEnded) {
    //决定pop还是还原
    CGFloat x = [recognizer translationInView:self.view].x;
    if (x >= 100) {
        [UIView animateWithDuration:0.25 animations:^{
            [AppDelegate shareDelegete].screenShotView.maskView.alpha = 0;
            self.view.transform = CGAffineTransformMakeTranslation(self.view.bounds.size.width, 0);
        } completion:^(BOOL finished) {
            [self popViewControllerAnimated:NO];
            [AppDelegate shareDelegete].screenShotView.hidden = YES;
            self.view.transform = CGAffineTransformIdentity;
        }];
    } else {
        [UIView animateWithDuration:0.25 animations:^{
            self.view.transform = CGAffineTransformIdentity;
            [AppDelegate shareDelegete].screenShotView.maskView.alpha = 0.5;
        } completion:^(BOOL finished) {
            [AppDelegate shareDelegete].screenShotView.hidden = YES;
        }];
    }
}
}

//保存截屏的数组
- (NSMutableArray<UIImage *> *)childVCImages{
if (!_childVCImages) {
    _childVCImages = [[NSMutableArray alloc] initWithCapacity:1];
}
return _childVCImages;
}

//截屏
#define WINDOW   [UIApplication sharedApplication].delegate.window
- (void)createScreenShot{
if (self.childViewControllers.count == self.childVCImages.count+1) {
    UIGraphicsBeginImageContextWithOptions(WINDOW.bounds.size, YES, 0);
    [WINDOW.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [self.childVCImages addObject:image];
}
}
#undef WINDOW

//手势代理
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
if (self.popRecognizerEnable == NO)     return NO;
if (self.viewControllers.count <= 1)    return NO;
if ([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]) {
    CGPoint point = [touch locationInView:gestureRecognizer.view];
    if (point.x < 80.0) {//设置手势触发区
        return YES;
    }
}
return NO;
}

//是否与其他手势共存,一般使用默认值(默认返回NO:不与任何手势共存)
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
if (self.recognizeSimultaneouslyEnable) {
    if ([otherGestureRecognizer isKindOfClass:NSClassFromString(@"UIScrollViewPanGestureRecognizer")] || [otherGestureRecognizer isKindOfClass:NSClassFromString(@"UIPanGestureRecognizer")] ) {
        return YES;
    }
}
return NO;
}
#pragma mark

@end

3、创建UINavigationController的扩展类<为了更方便的管理手势>
#import <UIKit/UIKit.h>
@interface UINavigationController (LLAddPart)
#pragma mark - 为系统类扩展属性
//是否响应自定义的滑动返回手势
- (void)setPopRecognizerEnable:(BOOL)popRecognizerEnable;
- (BOOL)popRecognizerEnable;

//自定义的滑动返回手势是否与其他手势共存,一般使用默认值(默认返回NO:不与任何手势共存)
- (void)setRecognizeSimultaneouslyEnable:(BOOL)recognizeSimultaneouslyEnable;
- (BOOL)recognizeSimultaneouslyEnable;
#pragma mark
@end

#import "UINavigationController+LLAddPart.h"
#import <objc/runtime.h>
@implementation UINavigationController (LLAddPart)
#pragma mark - 为系统类扩展属性
static BOOL _recognizeSimultaneouslyEnable;
static BOOL _popRecognizerEnable;
- (void)setRecognizeSimultaneouslyEnable:(BOOL)recognizeSimultaneouslyEnable {
NSNumber *t = @(recognizeSimultaneouslyEnable);
objc_setAssociatedObject(self, &_recognizeSimultaneouslyEnable, t, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)recognizeSimultaneouslyEnable {
NSNumber *t = objc_getAssociatedObject(self, &_recognizeSimultaneouslyEnable);
return [t boolValue];
}

- (void)setPopRecognizerEnable:(BOOL)popRecognizerEnable {
NSNumber *t = @(popRecognizerEnable);
objc_setAssociatedObject(self, &_popRecognizerEnable, t, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)popRecognizerEnable {
NSNumber *t = objc_getAssociatedObject(self, &_popRecognizerEnable);
return [t boolValue];
}
#pragma mark
@end

4、集成到项目中,在AppDelegate.h中声明一个属性<蒙版>和一个类方法,如下:

@property (nonatomic, strong) LLScreenShotView *screenShotView;
+ (instancetype)shareDelegete;

在AppDelegate.m中实现,如下:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];

ViewController *VC = [[ViewController alloc] init];
LLBaseNavigationController *baseNav = [[LLBaseNavigationController alloc] initWithRootViewController:VC];
self.window.rootViewController = baseNav;

return YES;
}

+ (instancetype)shareDelegete{
return (AppDelegate *)[UIApplication sharedApplication].delegate;
}

- (LLScreenShotView *)screenShotView{
if (!_screenShotView) {
    _screenShotView = [[LLScreenShotView alloc] init];
    _screenShotView.hidden = YES;
    [self.window insertSubview:_screenShotView atIndex:0];
}
return _screenShotView;
}

下面说一下易出错的地方:

  1. 截图应该添加在什么位置合适,首选主window上,添加到主window的最下方,可以用insert方法,添加到第0个位置。如果不显示,要看看rootViewController上,有没有其他的不透明的控件挡住了,也可以添加到rootViewController.view的最下方。
  2. 截屏之前,要做一个判断,保证每一个视图控制器只能截屏一次,避免了连点两下"下一页"后截屏数组中添加了两张截图,导致画面不一致
  3. 手势共存问题,最常见的就是与tableView的滑动删除冲突,建议去看下demo,不懂得,再去网上查一下手势共存的处理

二、自定义转场动画

<网上找了好多,代码都不全,所以我把我的代码全放了出来,供大家参考,上面有demo链接,也可以去下载>
1、自定义一个类,实现协议UINavigationControllerDelegate
#import <UIKit/UIKit.h>
@interface LLNavControllerDelegate : NSObject<UINavigationControllerDelegate>
@property (nonatomic, strong) NSString *presentTransition;
@property (nonatomic, strong) NSString *dismissTransition;
@end

#import "LLNavControllerDelegate.h"

@implementation LLNavControllerDelegate

- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC{
if (operation == UINavigationControllerOperationPush) {//push动画
    if(self.presentTransition){
        Class transition = NSClassFromString(self.presentTransition);
        return [transition new];
    }
}
else if (operation == UINavigationControllerOperationPop) {//pop动画
    if(self.dismissTransition){
        Class transition = NSClassFromString(self.dismissTransition);
        return [transition new];
    }
}
return nil;
}

@end

2、自定义转场动画

//push动画
#import <UIKit/UIKit.h>

@interface LLPresentAnimation : NSObject

@end

#import "LLPresentAnimation.h"

@interface LLPresentAnimation ()<UIViewControllerAnimatedTransitioning>

@end

@implementation LLPresentAnimation

- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext
{
    return 0.35f;
}

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext
{
UIView *fromView = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey].view;
UIView *toView   = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey].view;

UIView *containerView = [transitionContext containerView];
[containerView addSubview:toView];

NSTimeInterval duration = [self transitionDuration:transitionContext];
[UIView transitionFromView:fromView toView:toView duration:duration options:UIViewAnimationOptionTransitionFlipFromRight  completion:^(BOOL finished) {
    [transitionContext completeTransition:YES];
    fromView.transform = CGAffineTransformIdentity;
    toView.transform = CGAffineTransformIdentity;
}];
}

@end

--------华丽的分隔符--------

//pop动画
#import <UIKit/UIKit.h>

@interface LLDismissAnimation : NSObject

@end

#import "LLDismissAnimation.h"

@interface LLDismissAnimation ()<UIViewControllerAnimatedTransitioning>

@end

@implementation LLDismissAnimation

- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext
{
    return 0.35f;
}

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext
{
UIView *fromView = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey].view;
UIView *toView   = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey].view;

UIView *containerView = [transitionContext containerView];
[containerView addSubview:toView];

NSTimeInterval duration = [self transitionDuration:transitionContext];
[UIView transitionFromView:fromView toView:toView duration:duration options:UIViewAnimationOptionTransitionFlipFromLeft  completion:^(BOOL finished) {
    [transitionContext completeTransition:YES];
    fromView.transform = CGAffineTransformIdentity;
    toView.transform = CGAffineTransformIdentity;
}];
}

@end

3、在自定义的navgationController里面写上如下代码:

//首先声明属性
@property (nonatomic, strong) LLNavControllerDelegate   *transitionDelagate;

//在viewDidLoad中
self.transitionDelagate = [[LLNavControllerDelegate alloc] init];
self.transitionDelagate.presentTransition = @"LLPresentAnimation"; //自定义push动画
self.transitionDelagate.dismissTransition = @"LLDismissAnimation"; //自定义pop动画
self.delegate = self.transitionDelagate;

OK,大功告成,至于想要什么要的动画效果,各凭所需。。。
此导航继承于系统类UINavigationController,因此无需考虑性能问题,完全延续系统的push和pop方法,集成简单,同时,无任代码耦合度,可随时从项目中剥离。两个项目已上架,目前版本已十分完善,可放心使用。
觉得好,请给个star,谢谢!

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

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,016评论 4 62
  • 窗外蝉鸣,阳光炙热,课室的风扇吱呀吱呀,无一不让人心生烦躁。 少女望着窗外被风吹得沙沙响的叶子,赌气地想着,如果她...
    honey阿粥阅读 386评论 0 0
  • 1. \d,\w,\s,[a-zA-Z0-9],\b,.,*,+,?,x{3},^$分别是什么? \d — 数字字...
    王康_Wang阅读 176评论 0 0
  • 作为一个资深相亲失败人士,一个连续两年获得好人卡小能手冠军得主,我有什么资格来写一写相亲的问题呢?但正如末代皇帝溥...
    师爷苏阅读 328评论 0 0