iOS如何自定义控制器转场动画push详解

时间:2022-08-25 13:06:14

前言

最近有些空闲时间,整理了下最近做的项目,本文主要介绍了关于ios自定义控制器转场动画push的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

效果图:

iOS如何自定义控制器转场动画push详解

ios7 开始苹果推出了自定义转场的 api 。从此,任何可以用 coreanimation 实现的动画,都可以出现在两个 viewcontroller 的切换之间。并且实现方式高度解耦,这也意味着在保证代码干净的同时想要替换其他动画方案时只需简单改一个类名就可以了,真正体会了一把高颜值代码带来的愉悦感。

其实网上关于自定义转场动画的教程很多,这里我是希望同学们能易懂,易上手。

转场分两种push和modal,所以自定义转场动画也就肯定分两种,今天我们讲的是push

自定义转场动画push

首先搭建界面,添加4个按钮:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
- (void)addbutton{ 
 self.buttonarr = [nsmutablearray array]; 
 cgfloat margin=50;
 cgfloat width=(self.view.frame.size.width-margin*3)/2;
 cgfloat height = width;
 cgfloat x = 0;
 cgfloat y = 0;
 //列
 nsinteger col = 2;
 for (nsinteger i = 0; i < 4; i ++) {  
  x = margin + (i%col)*(margin+width);
  y = margin + (i/col)*(margin+height) + 150;
   
  uibutton *button = [uibutton buttonwithtype:uibuttontypecustom];
  button.frame = cgrectmake(x, y, width, height);
  button.layer.cornerradius = width * 0.5;
  [button addtarget:self action:@selector(btnclick:) forcontrolevents:uicontroleventtouchupinside];
  button.backgroundcolor = [uicolor colorwithred:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1.0];
  button.tag = i+1;
  [self.view addsubview:button];
  [self.buttonarr addobject:button];
 }
}

添加动画:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
- (void)setupbuttonanimation{ 
 [self.buttonarr enumerateobjectsusingblock:^(uibutton * _nonnull button, nsuinteger idx, bool * _nonnull stop) {  
  // positionanimation
  cakeyframeanimation *positionanimation = [cakeyframeanimation animationwithkeypath:@"position"];
  positionanimation.calculationmode = kcaanimationpaced;
  positionanimation.fillmode = kcafillmodeforwards;
  positionanimation.repeatcount = maxfloat;
  positionanimation.autoreverses = yes;
  positionanimation.timingfunction = [camediatimingfunction functionwithname:kcamediatimingfunctioneaseineaseout];
  positionanimation.duration = (idx == self.buttonarr.count - 1) ? 4 : 5+idx;
  uibezierpath *positionpath = [uibezierpath bezierpathwithovalinrect:cgrectinset(button.frame, button.frame.size.width/2-5, button.frame.size.height/2-5)];
  positionanimation.path = positionpath.cgpath;
  [button.layer addanimation:positionanimation forkey:nil];  
  // scalexaniamtion
  cakeyframeanimation *scalexaniamtion = [cakeyframeanimation animationwithkeypath:@"transform.scale.x"];
  scalexaniamtion.values = @[@1.0,@1.1,@1.0];
  scalexaniamtion.keytimes = @[@0.0,@0.5,@1.0];
  scalexaniamtion.repeatcount = maxfloat;
  scalexaniamtion.autoreverses = yes;
  scalexaniamtion.duration = 4+idx;
  [button.layer addanimation:scalexaniamtion forkey:nil];  
  // scaleyaniamtion
  cakeyframeanimation *scaleyanimation = [cakeyframeanimation animationwithkeypath:@"transform.scale.y"];
  scaleyanimation.values = @[@1,@1.1,@1.0];
  scaleyanimation.keytimes = @[@0.0,@0.5,@1.0];
  scaleyanimation.autoreverses = yes;
  scaleyanimation.repeatcount = yes;
  scaleyanimation.duration = 4+idx;
  [button.layer addanimation:scaleyanimation forkey:nil];  
 }];
}

界面搭建好了:

iOS如何自定义控制器转场动画push详解

然后想在push的时候实现自定义转场动画首先要遵守一个协议uinavigationcontrollerdelegate

苹果在 uinavigationcontrollerdelegate 中给出了几个协议方法,通过返回类型就可以很清楚地知道各自的具体作用。

?
1
2
//用来自定义转场动画
- (nullable id)navigationcontroller:(uinavigationcontroller *)navigationcontroller         animationcontrollerforoperation:(uinavigationcontrolleroperation)operation            fromviewcontroller:(uiviewcontroller *)fromvc             toviewcontroller:(uiviewcontroller *)tovc ns_available_ios(7_0);
?
1
2
//为这个动画添加用户交互
- (nullable id)navigationcontroller:(uinavigationcontroller *)navigationcontroller       interactioncontrollerforanimationcontroller:(id) animationcontroller ns_available_ios(7_0);

在第一个方法里只要返回一个准守uiviewcontrollerinteractivetransitioning协议的对象,并在里面实现动画即可

  • 创建继承自 nsobject 并且声明 uiviewcontrolleranimatedtransitioning 的的动画类。
  • 重载 uiviewcontrolleranimatedtransitioning 中的协议方法。
?
1
2
3
4
//返回动画时间
- (nstimeinterval)transitionduration:(nullable id)transitioncontext;
//将动画的代码写到里面即可
- (void)animatetransition:(id)transitioncontext;

首先我自定义一个名为lrtransitionpushcontroller的类继承于nsobject准守了uiviewcontrolleranimatedtransitioning协议

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
- (void)animatetransition:(id)transitioncontext{ 
 self.transitioncontext = transitioncontext; 
 //获取源控制器 注意不要写成 uitransitioncontextfromviewkey
 lrtransitionpushcontroller *fromvc = [transitioncontext viewcontrollerforkey:uitransitioncontextfromviewcontrollerkey];
 //获取目标控制器 注意不要写成 uitransitioncontexttoviewkey
 lrtransitionpopcontroller *tovc = [transitioncontext viewcontrollerforkey:uitransitioncontexttoviewcontrollerkey]; 
 //获得容器视图
 uiview *containview = [transitioncontext containerview];
 // 都添加到container中。注意顺序 目标控制器的view需要后面添加
 [containview addsubview:fromvc.view];
 [containview addsubview:tovc.view]; 
 uibutton *button = fromvc.button;
 //绘制圆形
 uibezierpath *startpath = [uibezierpath bezierpathwithovalinrect:button.frame];
  
 //创建两个圆形的 uibezierpath 实例;一个是 button 的 size ,另外一个则拥有足够覆盖屏幕的半径。最终的动画则是在这两个贝塞尔路径之间进行的
 //按钮中心离屏幕最远的那个角的点
 cgpoint finalpoint;
 //判断触发点在那个象限
 if(button.frame.origin.x > (tovc.view.bounds.size.width / 2)){
  if (button.frame.origin.y < (tovc.view.bounds.size.height / 2)) {
   //第一象限
   finalpoint = cgpointmake(0, cgrectgetmaxy(tovc.view.frame));
  }else{
   //第四象限
   finalpoint = cgpointmake(0, 0);
  }
 }else{
  if (button.frame.origin.y < (tovc.view.bounds.size.height / 2)) {
   //第二象限
   finalpoint = cgpointmake(cgrectgetmaxx(tovc.view.frame), cgrectgetmaxy(tovc.view.frame));
  }else{
   //第三象限
   finalpoint = cgpointmake(cgrectgetmaxx(tovc.view.frame), 0);
  }
 }
 cgpoint startpoint = cgpointmake(button.center.x, button.center.y);
 //计算向外扩散的半径 = 按钮中心离屏幕最远的那个角距离 - 按钮半径
 cgfloat radius = sqrt((finalpoint.x-startpoint.x) * (finalpoint.x-startpoint.x) + (finalpoint.y-startpoint.y) * (finalpoint.y-startpoint.y)) - sqrt(button.frame.size.width/2 * button.frame.size.width/2 + button.frame.size.height/2 * button.frame.size.height/2);
 uibezierpath *endpath = [uibezierpath bezierpathwithovalinrect:cgrectinset(button.frame, -radius, -radius)]; 
 //赋值给tovc视图layer的mask
 cashapelayer *masklayer = [cashapelayer layer];
 masklayer.path = endpath.cgpath;
 tovc.view.layer.mask = masklayer;
  
 cabasicanimation *maskanimation =[cabasicanimation animationwithkeypath:@"path"];
 maskanimation.fromvalue = (__bridge id)startpath.cgpath;
 maskanimation.tovalue = (__bridge id)endpath.cgpath;
 maskanimation.duration = [self transitionduration:transitioncontext];
 maskanimation.timingfunction = [camediatimingfunction functionwithname:kcamediatimingfunctioneaseineaseout];
 maskanimation.delegate = self;
 [masklayer addanimation:maskanimation forkey:@"path"];
}

在控制器里面用来自定义转场动画的方法里返回刚才自定义的动画类

?
1
2
3
4
5
6
7
- (id)navigationcontroller:(uinavigationcontroller *)navigationcontroller animationcontrollerforoperation:(uinavigationcontrolleroperation)operation fromviewcontroller:(uiviewcontroller *)fromvc toviewcontroller:(uiviewcontroller *)tovc{ 
 if (operation == uinavigationcontrolleroperationpush) {
  return [lrtranstionanimationpush new];
 }else{
  return nil;
 }
}

到此为止自定义转场动画就完成了

pop的动画只是把push动画反过来做一遍这里就不细讲了,有疑问的可以去看代码

添加滑动返回手势

上面说到这个方法是为这个动画添加用户交互的所以我们要在pop时实现滑动返回

最简单的方式应该就是利用uikit提供的uipercentdriveninteractivetransition类了,这个类已经实现了uiviewcontrollerinteractivetransitioning协议,同学men可以通过这个类的对象指定转场动画的完成百分比。

?
1
2
//为这个动画添加用户交互
- (nullable id)navigationcontroller:(uinavigationcontroller *)navigationcontroller       interactioncontrollerforanimationcontroller:(id) animationcontroller ns_available_ios(7_0);

第一步 添加手势

?
1
2
uipangesturerecognizer *gesturerecognizer = [[uipangesturerecognizer alloc] initwithtarget:self action:@selector(handlepan:)];
[self.view addgesturerecognizer:gesturerecognizer];

第二步 通过用户滑动的变化确定动画执行的比例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
- (void)handlepan:(uipangesturerecognizer *)gesturerecognizer { 
 /*调用uipercentdriveninteractivetransition的updateinteractivetransition:方法可以控制转场动画进行到哪了,
  当用户的下拉手势完成时,调用finishinteractivetransition或者cancelinteractivetransition,uikit会自动执行剩下的一半动画,
  或者让动画回到最开始的状态。*/  
 if ([gesturerecognizer translationinview:self.view].x>=0) {
  //手势滑动的比例
  cgfloat per = [gesturerecognizer translationinview:self.view].x / (self.view.bounds.size.width);
  per = min(1.0,(max(0.0, per)));  
  if (gesturerecognizer.state == uigesturerecognizerstatebegan) {   
   self.interactivetransition = [uipercentdriveninteractivetransition new];
   [self.navigationcontroller popviewcontrolleranimated:yes];   
  } else if (gesturerecognizer.state == uigesturerecognizerstatechanged){   
   if([gesturerecognizer translationinview:self.view].x ==0){    
    [self.interactivetransition updateinteractivetransition:0.01];    
   }else{    
    [self.interactivetransition updateinteractivetransition:per];
   }   
  } else if (gesturerecognizer.state == uigesturerecognizerstateended || gesturerecognizer.state == uigesturerecognizerstatecancelled){   
   if([gesturerecognizer translationinview:self.view].x == 0){    
    [self.interactivetransition cancelinteractivetransition];
    self.interactivetransition = nil;    
   }else if (per > 0.5) {    
    [ self.interactivetransition finishinteractivetransition];
   }else{
     
    [ self.interactivetransition cancelinteractivetransition];
   }
   self.interactivetransition = nil;
  }    
 } else if (gesturerecognizer.state == uigesturerecognizerstatechanged){
  [self.interactivetransition updateinteractivetransition:0.01];
  [self.interactivetransition cancelinteractivetransition];
 } else if ((gesturerecognizer.state == uigesturerecognizerstateended || gesturerecognizer.state == uigesturerecognizerstatecancelled)){  
  self.interactivetransition = nil;
 
}

第三步 在为动画添加用户交互的代理方法里返回uipercentdriveninteractivetransition的实例

?
1
2
3
- (id)navigationcontroller:(uinavigationcontroller *)navigationcontroller       interactioncontrollerforanimationcontroller:(id) animationcontroller {
 return self.interactivetransition;
}

如果感觉这篇文章对您有所帮助,顺手点个喜欢,谢谢啦

代码放在了github上大家可以下载

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

原文链接:http://www.cocoachina.com/ios/20171221/21621.html