美文网首页
简单的转场动画实现

简单的转场动画实现

作者: lizhi_boy | 来源:发表于2018-08-31 08:56 被阅读6次

1、建一个动画类并遵循UIViewControllerAnimatedTransitioning代理

@interface TestAnimation : NSObject<UIViewControllerAnimatedTransitioning>

2、实现协议方法

#pragma mark -- UIViewControllerAnimatedTransitioning

//动画效果添加
- (void)animateTransition:(nonnull id<UIViewControllerContextTransitioning>)transitionContext {
    //transitionContext上下文通过这个属性可以原控制器和目标控制器
    //原控制器
    UIViewController *scourVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    //目标控制器
    UIViewController *nextVC= [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    UIView *sourceView = nil;
    UIView *nextView = nil;
    CGFloat screen_width = [UIScreen mainScreen].bounds.size.width;
    CGFloat screen_height = [UIScreen mainScreen].bounds.size.height;
    
    if ([transitionContext respondsToSelector:@selector(viewForKey:)]) {
        sourceView = [transitionContext viewForKey:UITransitionContextFromViewKey];
        nextView = [transitionContext viewForKey:UITransitionContextToViewKey];
        
    }else{
        sourceView = scourVC.view;
        nextView = nextVC.view;
    }
    
    UIImageView *cricleView =[nextView subviews].firstObject;
    cricleView.backgroundColor = [UIColor redColor];
    cricleView.frame = CGRectMake(0, 90, 50, 50);
    nextView.frame =  CGRectMake(0,0,screen_width,screen_height);
    
    UIView *transtionView = [transitionContext containerView];
    
    [[transtionView subviews] enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.tag == 100) {
            [obj removeFromSuperview];
        }
    }];
    [transtionView addSubview:nextView];
    [transtionView addSubview:cricleView];

    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        
     cricleView.frame = CGRectMake(0, 0, screen_width, screen_height);
//   nextView.frame =  CGRectMake(0,0,screen_width,screen_height);
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:YES];
    }];
    
}

//动画持续时间
- (NSTimeInterval)transitionDuration:(nullable id<UIViewControllerContextTransitioning>)transitionContext {
    return 1.0;
}

实现的原理很简单:实际上就是在[transitionContext containerView]这个过渡视图里面做自己的动画效果。我这里是做一个图片放大的效果所以在目标控制器和源控制器都要有一个图片的视图,源控制器的视图仅做点击按钮使用。

   self.view.backgroundColor = [UIColor grayColor];
    UIImageView *cricleView = [UIImageView new];
    cricleView.contentMode = UIViewContentModeScaleAspectFill;
    cricleView.tag = 100;
    cricleView.backgroundColor = [UIColor grayColor];
    cricleView.image = [UIImage imageNamed:@"testpiture"];
    cricleView.frame = CGRectMake(0, 90,50,50);//这个frame在跳转动画类里面有修改(显示以修改的frame为准),这里的frame只是提供一个默认值。
    [self.view addSubview:cricleView];

相关文章

网友评论

      本文标题:简单的转场动画实现

      本文链接:https://www.haomeiwen.com/subject/ghnjwftx.html