一. 导航控制器
- 导航控制器分为三个区,分别是导航区,内容区,工具区,分别对应导航控制器的三个属性: navigationController.navigationBar; navigationController.viewControllers; navigationController.toolbar。
- 其中 navigationController.toolbar是默认隐藏的可以使用self.navigationController.toolbarHidden = NO;显示toolbar。
简单分析:
- UINavigationController是ViewController的父控制器。
- UINavigationController.view是个UILayoutContainerView,这是一个容器View。
- UILayoutContainerView里面有一个UINavigationTransitionView,这个View是做专场动画的(比如pop的动画)。
- UINavigationTransitionView里面有一个UIViewControllerWrapperView(暂时不知道干嘛的)。
1. navigationBar.translucent的影响
iOS 7.0之前,导航条拟物化风格,导航条是不透明(内容区在导航条下:64开始),但是iOS 7.0之后,导航条默认透明,由此就产生的一些问题,控制器的View为了得到如下布局就要设置一些属性:
① 对UILabel的影响
在控制器的View添加UILabel,如下:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
label.text = @"在view上";
label.backgroundColor = [UIColor redColor];
[self.view addSubview:label];
可以看出,他们的y都是0。
- 想要实现导航条半透明,内容从0开始,需要设置
// 透明全局(默认)
- (void)translucentAndAll{
self.navigationController.navigationBar.translucent = YES;
self.edgesForExtendedLayout = UIRectEdgeAll;
// self.automaticallyAdjustsScrollViewInsets = YES;
// self.extendedLayoutIncludesOpaqueBars = NO;
}
效果图如下:- 导航条透明,内容从64开始(0,iphonex 84)
//透明 内容从64开始
- (void)translucentAnd64{
self.navigationController.navigationBar.translucent = YES;
self.edgesForExtendedLayout = UIRectEdgeNone;
// self.automaticallyAdjustsScrollViewInsets = YES;
// self.extendedLayoutIncludesOpaqueBars = NO;
}
效果图如下:- 不透明,内容从0开始
- (void)noTranslucentAndAll{
self.navigationController.navigationBar.translucent = NO;
self.extendedLayoutIncludesOpaqueBars = YES;
// self.edgesForExtendedLayout = UIRectEdgeNone;
}
效果图如下:- 不透明,内容从64开始
- (void)noTranslucentAnd64{
//不透明, 默认就是从64开始的
self.navigationController.navigationBar.translucent = NO;
// self.edgesForExtendedLayout = UIRectEdgeNone;
}
效果图如下:可以看出,不同情况下,当y都是为0的时候,系统会自动判断是从父view的0开始还是从导航栏下方开始(这点和scrollView不一样, scrollView是系统自动修改contentOffset的值)。
这关于更多四个属性的介绍:
navigationBar.translucent
edgesForExtendedLayout
automaticallyAdjustsScrollViewInsets
extendedLayoutIncludesOpaqueBars
请移步待定
② 对scrollView的影响
- 当我们添加如下代码,y值为0,什么都不设置的时候
- (void)viewDidLoad {
UILabel *labelscr = [[UILabel alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width-200, 0, 200, 200)];
labelscr.text = @"在scrollview上";
labelscr.backgroundColor = [UIColor yellowColor];
[_scrollView addSubview:labelscr];
}
- (void)viewWillLayoutSubviews{
[super viewWillLayoutSubviews];
[_scrollView setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 100)];
[_scrollView setContentSize:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height*1.5)];
}
我们会发现效果图如下:因为默认的self.automaticallyAdjustsScrollViewInsets = YES,系统会自动调整scrollView的contentOffset(contentOffset内部又是通过修改bounds值来改变的)。
- 当我们设置 self.automaticallyAdjustsScrollViewInsets = NO或者_scrollView.contentInsetAdjustmentBehavior = NO。
可以发现, 系统不会自动设置偏移了。
我们也可以通过打断点来验证是系统修改了contentOffset的值,如下图:- 当然,如果导航条不透明的时候,就没有偏移这回事了,都是从64开始算的。
比如,添加以下代码:
self.navigationController.navigationBar.translucent = NO;
效果图如下:2. items数组
- navigationBar里面管理着一个items数组,里面装的是控制器的item,这个items数组和navigationController.viewControllers是对应的。
- item是UINavigationItem类型,继承于NSObject,可以看作是一个model,item里面有title等属性,来记录着导航条的信息,每次进栈和出栈的时候都会更新这里面的数据。
注意:如果在导航条上面添加东西,要注意移除
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.navigationController.navigationBar addSubview:_tview];
}
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[_tview removeFromSuperview];
}
3. 设置全透明
可以通过self.navigationController.navigationBar.translucent = NO来设置不透明或者YES设置半透明, 但是如何设置全透明呢?
//全透明 放一个全透明图片
- (void)transluentStyle{
[self.navigationController.navigationBar setBackgroundImage:self.image forBarMetrics:UIBarMetricsDefault];
}
//画个透明图片
- (UIImage*)image{
UIGraphicsBeginImageContext(CGSizeMake(100, 100));
[[[UIColor whiteColor] colorWithAlphaComponent:0] setFill];
UIRectFill(CGRectMake(0, 0, 100, 100));
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
效果图如下:实际上设置导航条的背景图片是设置导航条的_UIBarBackground这个属性
4. 去掉黑线
导航条下方默认有一条黑线, 但是有时候我们不想要这个黑线
观察黑线的位置, 发现黑线的坐标是:黑线的y是64,高度0.33,超出导航条的位置,所以我们设置
self.navigationController.navigationBar.clipsToBounds = YES;
即可隐藏黑线。
另外我们也可以遍历到黑线,然后隐藏,如下:
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *iamgeV = [self findBackLineImageV:self.navigationController.navigationBar];
iamgeV.hidden = YES;
}
- (UIImageView *)findBackLineImageV:(UIView*)view{
if([view isKindOfClass:[UIImageView class]] && view.frame.size.height <= 1){
return (UIImageView*)view;
}
NSArray *viewAry = view.subviews;
for (int i = 0; i < viewAry.count; i++) {
UIView *tmpV = [self findBackLineImageV:viewAry[I]];
if (tmpV) {
return (UIImageView*)tmpV;
}
}
return nil;
}
5. 设置item间距、修改返回按钮图片、隐藏导航条
首先要知道UINavigationItem和UIBarButtonItem区别,当我们在控制器的View页面:
- self.navigationItem.title = @"Item间距" 和 self.title = @"Item间距" 是一个意思。
- self.navigationController.navigationBar.items里面装的就是UINavigationItem类型的item,这个items数组和self.navigationController.viewControllers是一一对应的。
- 通过self.navigationItem访问title、titleView、backBarButtonItem、leftBarButtonItems等属性。
- self.navigationItem是UINavigationItem类型的,backBarButtonItem是UIBarButtonItem类型的。
- 他们的继承关系也不同
UINavigationItem : NSObject
UIBarButtonItem : UIBarItem : NSOject
① 如何设置item间距
设置间距可以添加UIBarButtonSystemItemFixedSpace,并设置宽度:
NSMutableArray *barItems = [NSMutableArray array];
UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithTitle:@"Nav" style:UIBarButtonItemStylePlain target:self action:@selector(showNav)];
UIBarButtonItem *barItemSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
barItemSpace.width = 60; //设置宽度
UIBarButtonItem *barItemT = [[UIBarButtonItem alloc] initWithTitle:@"view" style:UIBarButtonItemStylePlain target:self action:@selector(showNavTwo)];
[barItems addObject:barItem];
[barItems addObject:barItemSpace];
[barItems addObject:barItemT];
self.navigationItem.rightBarButtonItems = barItems;
② 如何修改系统返回按钮的图片
//2. 修改系统返回按钮的图片
- (void)backArrowImage{
UIImage *image = [UIImage imageNamed:@"arrow.png"];
image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//系统要求要同时设置
self.navigationController.navigationBar.backIndicatorImage = image;
self.navigationController.navigationBar.backIndicatorTransitionMaskImage = image;
}
③ 如何隐藏导航条
隐藏导航条有两种方法:
- 这个是导航控制器的方法
self.navigationController.navigationBarHidden = YES;
隐藏之后打断点:
(lldb) po self.navigationController.navigationBar
<UINavigationBar: 0x100a091b0; frame = (0 -44; 375 44); opaque = NO; autoresize = W; layer = <CALayer: 0x2838d35c0>>
(lldb) po [self.navigationController.navigationBar superview]
nil
可以发现,导航控制器的隐藏方法是把导航条y往上移动44,并且remove掉。
- 这个是导航条的方法
self.navigationController.navigationBar.hidden = YES;
隐藏之后打断点:
(lldb) po self.navigationController.navigationBar
<UINavigationBar: 0x100706bb0; frame = (0 44; 375 44); hidden = YES; opaque = NO; autoresize = W; layer = <CALayer: 0x283e94800>>
(lldb) po [self.navigationController.navigationBar superview]
<UILayoutContainerView: 0x115d04680; frame = (0 0; 375 812); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x281538540>; layer = <CALayer: 0x281b46520>>
可以发现,导航条的隐藏方法是直接设置hidden = YES。
总结:
- 导航控制器的隐藏方法是把导航条y往上移动44,并且remove掉。
- 导航条的隐藏方法是直接设置hidden = YES。
- 侧滑返回手势是否失效
① 侧滑返回手势是依赖于导航条的,导航控制器的隐藏方法最终把导航条remove掉了,所以侧滑返回手势也没了。
② 导航条的隐藏方法是直接设置hidden = YES,所以侧滑返回手势还在。
6. 模仿系统的pop动画
观察系统的pop动画,发现系统的pop动画主要做了以下几件事:
- 添加一个pan手势
- 将pop到的view放在当前view下面
- 移动两个view的位置
- 导航栏动画
下面我们就模仿系统的pop动画,代码如下:
#import "EOCEOCAnimaTheoryVC.h"
@implementation EOCEOCAnimaTheoryVC
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"动画原理";
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
[self.view addGestureRecognizer:panGesture];
}
/*
1 当前的控制器view坐标的移动
2 下一个控制器view的坐标移动
*/
- (void)panGesture:(UIPanGestureRecognizer*)gesture{
// 获取 当前view(fromview) pop的view(toView)
//父View是UIViewControllerWrapperView
UIView *containView = [self.view superview];
UIView *fromView = self.view;
UIView *toView = nil;
NSArray *viewCtrAry = self.navigationController.viewControllers;
if (viewCtrAry.count >= 2) {
UIViewController *toViewCtr = viewCtrAry[viewCtrAry.count-2];
toView = toViewCtr.view;
}
//把toView添加到它的父View上, 自己的下面
[containView insertSubview:toView belowSubview:fromView];
CGPoint movePoint = [gesture translationInView:self.view];
[gesture setTranslation:CGPointZero inView:self.view];
float moveWidth = movePoint.x;
// UINavigationBar *preBar;(UINavigationBar动画待完成)
//手势开始
if (gesture.state == UIGestureRecognizerStateBegan) {
toView.frame = CGRectMake(-toView.frame.size.width, toView.frame.origin.y, toView.frame.size.width, toView.frame.size.height);
//手势改变
}else if (gesture.state == UIGestureRecognizerStateChanged){
if (movePoint.x > 0) { //从左往右滑动
// moveWidth *scale
toView.frame = CGRectMake(toView.frame.origin.x + moveWidth, toView.frame.origin.y, toView.frame.size.width, toView.frame.size.height);
fromView.frame = CGRectMake(fromView.frame.origin.x + moveWidth, fromView.frame.origin.y, fromView.frame.size.width, fromView.frame.size.height);
}
//手势结束
} else {
if (fromView.frame.origin.x > [UIScreen mainScreen].bounds.size.width/2) {
// pop
[UIView animateWithDuration:0.4 animations:^{
toView.frame = CGRectMake(0, toView.frame.origin.y, toView.frame.size.width, toView.frame.size.height);
fromView.frame = CGRectMake(fromView.frame.size.width, fromView.frame.origin.y, fromView.frame.size.width, fromView.frame.size.height);
} completion:^(BOOL finished) {
NSMutableArray *viewAry = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
[viewAry removeLastObject];
self.navigationController.viewControllers = viewAry;
}];
} else {
// 还原
[UIView animateWithDuration:0.4 animations:^{
fromView.frame = CGRectMake(0, fromView.frame.origin.y, fromView.frame.size.width, fromView.frame.size.height);
toView.frame = CGRectMake(-toView.frame.size.width, toView.frame.origin.y, toView.frame.size.width, toView.frame.size.height);
} completion:^(BOOL finished) {
}];
}
}
}
@end
即可实现模仿系统的pop动画。
7. 替换系统侧滑手势为全局滑动返回
思路:就是把系统侧滑手势的target和action替换为自己的pan手势的target和action
#import "EOCNavSysGestureVC.h"
#import <objc/runtime.h>
@implementation EOCNavSysGestureVC
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"替换系统侧滑手势为全局滑动返回";
//interactivePopGestureRecognizer是UIGestureRecognizer类型的
NSArray *targets = [self.navigationController.interactivePopGestureRecognizer valueForKey:@"targets"];
id target = [[targets lastObject] valueForKey:@"target"];
SEL actionSel = NSSelectorFromString(@"handleNavigationTransition:");
//将系统的手势的action和target放到下面panGesture上
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:target action:actionSel];
[self.view addGestureRecognizer:panGesture];
[self scanMethods:NSClassFromString(@"UIScreenEdgePanGestureRecognizer")];
}
//使用runtime获取类的方法列表
- (void)scanMethods:(Class)class{
unsigned int outCount = 0;
Method *methods = class_copyMethodList(class, &outCount);
for (int i = 0; i < outCount; i++) {
SEL sel = method_getName(methods[I]);
NSLog(@"%@", NSStringFromSelector(sel));
}
}
@end
效果图省略。
8. 自定义导航控制器的pop动画
要实现自定义导航控制器的pop动画,我们需要自定义导航控制器,并实现导航控制器的代理方法,我们先看这个代理方法。
//返回动画对象
- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
animationControllerForOperation:(UINavigationControllerOperation)operation
fromViewController:(UIViewController *)fromVC
toViewController:(UIViewController *)toVC NS_AVAILABLE_IOS(7_0);
这个代理方法要求我们返回遵守UIViewControllerAnimatedTransitioning协议的对象,所以我们创建EOCNavAnimation对象,并遵守协议,代码如下:
EOCNavAnimation.h文件
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface EOCNavAnimation : NSObject<UIViewControllerAnimatedTransitioning, CAAnimationDelegate>
@end
EOCNavAnimation.m文件
#import "EOCNavAnimation.h"
@implementation EOCNavAnimation{
id <UIViewControllerContextTransitioning> _transitionContext;
}
// 动画的时间
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext{
return 0.5;
}
// 动画的过程
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext{
// 获取 toView(ToViewCtr)/fromView(fromViewCtr)
_transitionContext = transitionContext;
//将要返回的VC
UIViewController *toViewCtr = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
//从哪个界面返回的VC
UIViewController *fromViewCtr = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
UIView *transferView = transitionContext.containerView;
//界面的动画添加到containerView里面,真正执行动画的还是UINavigationTransitionView
// 规定的 如果用transferView.superview导航条会被遮住
// transferView = [transferView superview]; // UINavigationTransitionView
UIView *fromView = fromViewCtr.view;
[transferView insertSubview:toViewCtr.view belowSubview:fromViewCtr.view];
[self animationOneFromView:fromView transitionContext:transitionContext];
//[self animationTwoTransferView:transferView];
}
//我们自定义的第一种动画
- (void)animationOneFromView:(UIView*)fromView transitionContext:(id <UIViewControllerContextTransitioning>)transitionContext{
[UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
fromView.frame = CGRectMake(fromView.frame.size.width, fromView.frame.origin.y, fromView.frame.size.width, fromView.frame.size.height);
} completion:^(BOOL finished) {
// 务必 compelte Context
[transitionContext completeTransition:YES];
}];
}
//我们自定义的第二种动画
- (void)animationTwoTransferView:(UIView*)transferView{
CATransition *caTrans = [CATransition animation];
caTrans.type = @"cube";
caTrans.subtype = @"fromLeft";
caTrans.duration = [self transitionDuration:_transitionContext];
caTrans.fillMode = kCAFillModeForwards;
caTrans.delegate = self;
caTrans.removedOnCompletion = NO;
[transferView.layer addAnimation:caTrans forKey:nil];
[transferView exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
}
// 动画的结束
- (void)animationEnded:(BOOL) transitionCompleted{
}
//CATransition 代理方法
// 动画结束
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
[_transitionContext completeTransition:YES];
}
@end
动画搞定,接下来我们就要自定义导航控制器了,自定义EOCNavViewCtr,继承于UINavigationController,遵守UINavigationControllerDelegate协议,设置其代理为self,并实现其代理方法,代码如下:
// 返回动画对象
- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
animationControllerForOperation:(UINavigationControllerOperation)operation
fromViewController:(UIViewController *)fromVC
toViewController:(UIViewController *)toVC {
VC = fromVC;
NSLog(@"fromVC -- %@",fromVC);
//如果是pop返回, 就用我们自己的动画对象
if (operation == UINavigationControllerOperationPop) {
return [[EOCNavAnimation alloc] init];
}
return nil;
}
在这个方法里面,如果是pop,我们就用我们自定义的动画对象,至此就完成了自定义导航控制器的pop动画,当我们用EOCNavViewCtr做一些pop操作的时候用的就是我们自己的动画了。
点击左上角返回按钮,动画效果如下:但是,自定义导航控制器之后,系统默认的侧滑返回失效了,为了学习更多的导航控制器的代理方法,我们打算给我们自定义的导航控制器添加一个pan手势,从而实现滑动返回的效果。
我们需要实现这个方法,控制动画进度,这个方法需要返回一个遵守UIViewControllerInteractiveTransitioning协议的类,系统有遵守这个协议的类了,我们直接用系统的。
// 返回动画进度对象
- (nullable id <UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController
interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>) animationController {
if ([animationController isKindOfClass:[EOCNavAnimation class]]) {
return percentAnimation;
}
return nil;
}
完整的EOCNavViewCtr.m文件代码如下:
#import "EOCNavViewCtr.h"
#import "EOCNavAnimation.h"
@interface EOCNavViewCtr ()<UINavigationControllerDelegate>{
//系统提供了遵守UIViewControllerInteractiveTransitioning协议的类
UIPercentDrivenInteractiveTransition *percentAnimation;
UIViewController *VC; //保存从哪个界面pop的, 留着我们取消pop使用
}
@end
@implementation EOCNavViewCtr
- (void)viewDidLoad {
[super viewDidLoad];
self.delegate = self;
//添加滑动手势
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
[self.view addGestureRecognizer:panGesture];
}
- (void)panGesture:(UIPanGestureRecognizer*)gesture{
// 获取 当前view(fromview) pop的view(toView)
CGPoint movePoint = [gesture translationInView:self.view];
float precent = movePoint.x/[UIScreen mainScreen].bounds.size.width;
//开始
if (gesture.state == UIGestureRecognizerStateBegan) {
percentAnimation = [[UIPercentDrivenInteractiveTransition alloc] init];
[self popViewControllerAnimated:YES];
//改变
} else if (gesture.state == UIGestureRecognizerStateChanged){
[percentAnimation updateInteractiveTransition:precent];
} else {
//完成
if (percentAnimation.percentComplete > 0.5) { //pop
[percentAnimation finishInteractiveTransition];
} else { //取消pop
[percentAnimation cancelInteractiveTransition];
[self pushViewController:VC animated:NO];
}
percentAnimation = nil;
}
}
#pragma mark - 导航控制器代理方法
// 返回动画进度对象
- (nullable id <UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController
interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>) animationController {
if ([animationController isKindOfClass:[EOCNavAnimation class]]) {
return percentAnimation;
}
return nil;
}
// 返回动画对象
- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
animationControllerForOperation:(UINavigationControllerOperation)operation
fromViewController:(UIViewController *)fromVC
toViewController:(UIViewController *)toVC {
VC = fromVC;
NSLog(@"fromVC -- %@",fromVC);
//如果是pop返回, 就用我们自己的动画对象
if (operation == UINavigationControllerOperationPop) {
return [[EOCNavAnimation alloc] init];
}
return nil;
}
@end
滑动返回动画效果如上图,不再赘述。