iOS使用系統(tǒng)的導(dǎo)航欄,自定義滑動(dòng)返回手勢(shì)與轉(zhuǎn)場(chǎng)(過場(chǎng))動(dòng)畫

其實(shí),上天給了我十萬條理由讓我去使用系統(tǒng)的導(dǎo)航欄,然而,僅僅只因?yàn)橐粭l,我不得不放棄,我們坑爹的產(chǎn)品經(jīng)理不喜歡。。。
于是,我走上了一條自定義導(dǎo)航欄(花樣作死)的不歸路。。。

一、自定義滑動(dòng)返回手勢(shì)與滑動(dòng)動(dòng)畫

代碼有點(diǎn)多,為了大家能看懂,我全放在這里,相信同學(xué)們看完都能自己寫出來,建議去github下個(gè)demo,

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

我實(shí)現(xiàn)了個(gè)簡(jiǎn)單的動(dòng)畫效果,如下圖:

IMG_0197.PNG

首先說一下思路:

  1. 重寫push方法,在每一次push的時(shí)候,對(duì)當(dāng)前屏幕進(jìn)行截圖,保存到一個(gè)數(shù)組中
  2. 重寫pop的一系列方法,在每一次pop的時(shí)候,移除數(shù)組中相對(duì)應(yīng)的截圖
  3. 自定義返回手勢(shì),滑動(dòng)的時(shí)候,將數(shù)組中的最后一張圖片,添加到當(dāng)前視圖的下方,產(chǎn)生了上一個(gè)視圖在當(dāng)前視圖下方的錯(cuò)覺
    思路很簡(jiǎn)單,不過實(shí)現(xiàn)起來,還需要些技巧

下面上代碼:
1、首先,創(chuàng)建一個(gè)簡(jiǎn)單的蒙版
#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、創(chuàng)建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; //保存截屏的數(shù)組
@property (nonatomic, strong) LLNavControllerDelegate   *transitionDelagate;
@end

@implementation LLBaseNavigationController
- (void)loadView{
[super loadView];
//self.interactivePopGestureRecognizer.delegate = self; //系統(tǒng)的返回手勢(shì)代理
self.interactivePopGestureRecognizer.enabled = NO;      //屏蔽系統(tǒng)的返回手勢(shì)
self.transitionDelagate = [[LLNavControllerDelegate alloc] init];
self.transitionDelagate.presentTransition = @"LLPresentAnimation"; //自定義push動(dòng)畫
self.transitionDelagate.dismissTransition = @"LLDismissAnimation"; //自定義pop動(dòng)畫
self.delegate = self.transitionDelagate;
}

- (void)viewDidLoad{
[super viewDidLoad];
UIPanGestureRecognizer *popRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragging:)];
popRecognizer.delegate = self;
[self.view addGestureRecognizer:popRecognizer];         //自定義的滑動(dòng)返回手勢(shì)
self.popRecognizerEnable = YES;                         //默認(rèn)相應(yīng)自定義的滑動(dòng)返回手勢(shì)
}

#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個(gè)子控制器,停止拖拽
if (self.viewControllers.count <= 1) return;
//在x方向上移動(dòng)的距離
CGFloat tx = [recognizer translationInView:self.view].x;
//在x方向上移動(dòng)的距離除以屏幕的寬度
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){
    //移動(dòng)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;
        }];
    }
}
}

//保存截屏的數(shù)組
- (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

//手勢(shì)代理
- (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) {//設(shè)置手勢(shì)觸發(fā)區(qū)
        return YES;
    }
}
return NO;
}

//是否與其他手勢(shì)共存,一般使用默認(rèn)值(默認(rèn)返回NO:不與任何手勢(shì)共存)
- (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、創(chuàng)建UINavigationController的擴(kuò)展類<為了更方便的管理手勢(shì)>
#import <UIKit/UIKit.h>
@interface UINavigationController (LLAddPart)
#pragma mark - 為系統(tǒng)類擴(kuò)展屬性
//是否響應(yīng)自定義的滑動(dòng)返回手勢(shì)
- (void)setPopRecognizerEnable:(BOOL)popRecognizerEnable;
- (BOOL)popRecognizerEnable;

//自定義的滑動(dòng)返回手勢(shì)是否與其他手勢(shì)共存,一般使用默認(rèn)值(默認(rèn)返回NO:不與任何手勢(shì)共存)
- (void)setRecognizeSimultaneouslyEnable:(BOOL)recognizeSimultaneouslyEnable;
- (BOOL)recognizeSimultaneouslyEnable;
#pragma mark
@end

#import "UINavigationController+LLAddPart.h"
#import <objc/runtime.h>
@implementation UINavigationController (LLAddPart)
#pragma mark - 為系統(tǒng)類擴(kuò)展屬性
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、集成到項(xiàng)目中,在AppDelegate.h中聲明一個(gè)屬性<蒙版>和一個(gè)類方法,如下:

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

在AppDelegate.m中實(shí)現(xiàn),如下:
- (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;
}

下面說一下易出錯(cuò)的地方:

  1. 截圖應(yīng)該添加在什么位置合適,首選主window上,添加到主window的最下方,可以用insert方法,添加到第0個(gè)位置。如果不顯示,要看看rootViewController上,有沒有其他的不透明的控件擋住了,也可以添加到rootViewController.view的最下方。
  2. 截屏之前,要做一個(gè)判斷,保證每一個(gè)視圖控制器只能截屏一次,避免了連點(diǎn)兩下"下一頁"后截屏數(shù)組中添加了兩張截圖,導(dǎo)致畫面不一致
  3. 手勢(shì)共存問題,最常見的就是與tableView的滑動(dòng)刪除沖突,建議去看下demo,不懂得,再去網(wǎng)上查一下手勢(shì)共存的處理

二、自定義轉(zhuǎn)場(chǎng)動(dòng)畫

<網(wǎng)上找了好多,代碼都不全,所以我把我的代碼全放了出來,供大家參考,上面有demo鏈接,也可以去下載>
1、自定義一個(gè)類,實(shí)現(xiàn)協(xié)議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動(dòng)畫
    if(self.presentTransition){
        Class transition = NSClassFromString(self.presentTransition);
        return [transition new];
    }
}
else if (operation == UINavigationControllerOperationPop) {//pop動(dòng)畫
    if(self.dismissTransition){
        Class transition = NSClassFromString(self.dismissTransition);
        return [transition new];
    }
}
return nil;
}

@end

2、自定義轉(zhuǎn)場(chǎng)動(dòng)畫

//push動(dòng)畫
#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動(dòng)畫
#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動(dòng)畫
self.transitionDelagate.dismissTransition = @"LLDismissAnimation"; //自定義pop動(dòng)畫
self.delegate = self.transitionDelagate;

OK,大功告成,至于想要什么要的動(dòng)畫效果,各憑所需。。。
此導(dǎo)航繼承于系統(tǒng)類UINavigationController,因此無需考慮性能問題,完全延續(xù)系統(tǒng)的push和pop方法,集成簡(jiǎn)單,同時(shí),無任代碼耦合度,可隨時(shí)從項(xiàng)目中剝離。兩個(gè)項(xiàng)目已上架,目前版本已十分完善,可放心使用。
覺得好,請(qǐng)給個(gè)star,謝謝!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,002評(píng)論 6 542
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,400評(píng)論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 178,136評(píng)論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,714評(píng)論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,452評(píng)論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,818評(píng)論 1 328
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,812評(píng)論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,997評(píng)論 0 290
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,552評(píng)論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,292評(píng)論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,510評(píng)論 1 374
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,035評(píng)論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,721評(píng)論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,121評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,429評(píng)論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,235評(píng)論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,480評(píng)論 2 379

推薦閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,170評(píng)論 4 61
  • 窗外蟬鳴,陽光炙熱,課室的風(fēng)扇吱呀吱呀,無一不讓人心生煩躁。 少女望著窗外被風(fēng)吹得沙沙響的葉子,賭氣地想著,如果她...
    honey阿粥閱讀 394評(píng)論 0 0
  • 1. \d,\w,\s,[a-zA-Z0-9],\b,.,*,+,?,x{3},^$分別是什么? \d — 數(shù)字字...
    王康_Wang閱讀 180評(píng)論 0 0
  • 作為一個(gè)資深相親失敗人士,一個(gè)連續(xù)兩年獲得好人卡小能手冠軍得主,我有什么資格來寫一寫相親的問題呢?但正如末代皇帝溥...
    師爺蘇閱讀 343評(píng)論 0 0