增加dismissViewControllerAnimated()

时间:2016-03-19 15:06:03

标签: ios swift uiviewcontroller

我一直试图弄清楚如何增加dismissViewControllerAnimated(true, completion: nil)的持续时间,但似乎无法在Apples documentation中找到答案。我的视图控制器从下到上显示动画,并在解除时以相反的顺序运行。我希望动画更慢,比如0.5秒,任何建议?

2 个答案:

答案 0 :(得分:2)

您必须为视图控制器使用自定义过渡。请看一下这个精彩的教程,以帮助您入门:http://www.appcoda.com/custom-view-controller-transitions-tutorial/

在此处添加主要代码,以防将来删除链接:

创建一个名为CustomPresentAnimationController的新类,并使其成为NSObject的子类。 class CustomPresentAnimationController:NSObject,UIViewControllerAnimatedTransitioning

UIViewControllerAnimatedTransitioning协议有两个必需的方法,接下来我们将添加。将以下方法添加到类中。

    func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
        return 2.5
    }

    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {

    let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!
    let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!
    let finalFrameForVC = transitionContext.finalFrameForViewController(toViewController)
    let containerView = transitionContext.containerView()
    let bounds = UIScreen.mainScreen().bounds
    toViewController.view.frame = CGRectOffset(finalFrameForVC, 0, bounds.size.height)
    containerView.addSubview(toViewController.view)

    UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: .CurveLinear, animations: {
        fromViewController.view.alpha = 0.5
        toViewController.view.frame = finalFrameForVC
        }, completion: {
            finished in
            transitionContext.completeTransition(true)
            fromViewController.view.alpha = 1.0
    })}

动画控制器完成后,我们需要将其链接到故事板segue。 打开ItemsTableViewController.swift文件并更改类声明,如图所示。

class ItemsTableViewController: UITableViewController, UIViewControllerTransitioningDelegate {

在此类中添加此内容以处理segue:

let customPresentAnimationController = CustomPresentAnimationController()

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "showAction" {
        let toViewController = segue.destinationViewController as UIViewController
        toViewController.transitioningDelegate = self
    }
}

将以下UIViewControllerTransitioningDelegate方法添加到课程中。这将返回我们的自定义动画控制器的实例。

func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    return customPresentAnimationController
}

该文章原作者的所有信用。

答案 1 :(得分:0)

您可以尝试这样的事情:

CATransaction.begin()
CATransaction.setAnimationDuration(2.0)
dismissViewControllerAnimated(true, completion: nil)
CATransaction.commit()