如何在解除视图控制器时获得淡出动画

时间:2017-11-30 11:08:08

标签: ios objective-c uiviewcontroller

我的View Controller中有一个Image视图。我想在向视图控制器的下方识别平移手势时关闭视图控制器。虽然我已经用Pan手势取消了视图控制器,但我试图找出如何在解除之前添加动画,就像在iPhone中的照片应用程序中一样。

 -(void)addPanGesture{

    UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dismissViewGes:)];
    gestureRecognizer.delegate = self;
    [self.view addGestureRecognizer:gestureRecognizer];


}



-(void)dismissViewGes:(UIPanGestureRecognizer *)gesture {


    CGPoint velocity = [gesture velocityInView:self.view];


    if(velocity.y > 0)
    {



        CATransition *transition = [[CATransition alloc]init];
        transition.duration = 2;
        [transition setValue:[NSNumber numberWithFloat:0.5f] forKey:kCATransitionFade];
        transition.subtype = kCATransitionFromTop;
        [self.view.layer addAnimation:transition forKey:nil];

        [[NetWrapper shared] addRemovedController:self];
        [self dismissViewControllerAnimated:NO completion:nil];


    }

}

我尝试添加一个CATransition,希望淡出动画能够正常工作,但它不起作用,一旦应用了平移手势,视图就会消失。

如果像在照片应用程序中一样解除视图,我怎么能添加淡出效果。

Photo viewer. I have this right now and when i use Pan gesture on this view it gets dismissed. But i want to add an animation so that it gets dismissed as in the second picture

This is the animation I want to achieve

3 个答案:

答案 0 :(得分:3)

Swift 4.2,iOS 11

这是使用扩展名的一种优雅方式:

UIViewController

然后,您可以在函数中或private func dismissVC() { let transition = CATransition().fadeTransition() navigationController?.view.layer.add(transition, forKey: kCATransition) navigationController?.popViewController(animated: false) } 的操作按钮内编写以下三行代码:

DataClient dataClient = Wearable.getDataClient(this);

答案 1 :(得分:2)

试试这个:

@IBAction func clickDismiss(_ sender: Any) {
    let transition: CATransition = CATransition()
    transition.duration = 0.5
    transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    transition.type = kCATransitionFade
    transition.subtype = kCATransitionFromBottom
    self.view.window!.layer.add(transition, forKey: nil)
    self.dismiss(animated: false, completion: nil)
}

我提出了一个SubViewController并在其上添加了一个UIButton。将这些代码添加到按钮点击事件中,并为我工作。

答案 2 :(得分:0)

如果您需要在呈现或解除ViewController时添加动画,您应该使用UIViewControllerAnimatedTransitioning,这里有类似的答案: How do I do a Fade/No transition between view controllers

如果需要它是交互式的,可以使用UIPercentDrivenInteractiveTransition,它是一个控制百分比转换的类。

关于这一切,Apple提供了很好的示例代码: https://developer.apple.com/library/content/samplecode/CustomTransitions/Introduction/Intro.html 它有点旧,但很简单。