没有动画的自定义视图控制器演示

Custom view controller presentation without animation

我有一些自定义模式演示和自定义控制器要演示(UIViewController 的子类)。它是它自己的转换委托和 returns 一些动画转换对象和演示控制器。我使用动画过渡对象在呈现时将呈现的视图添加到容器视图,并在关闭时将其删除,当然还有动画效果。我使用演示控制器添加一些辅助子视图。

public final class PopoverPresentationController: UIPresentationController {
    private let touchForwardingView = TouchForwardingView()

    override public func presentationTransitionWillBegin() {
        super.presentationTransitionWillBegin()
        self.containerView?.insertSubview(touchForwardingView, atIndex: 0)
    }
}

public final class PopoverAnimatedTransitioning: NSObject, UIViewControllerAnimatedTransitioning {

    func setupView(containerView: UIView, presentedView: UIView) {
        //adds presented view to container view 
    }

    public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        //1. setup views 
        //2. animate presentation or dismissal
    }
}

public class PopoverViewController: UIViewController, UIViewControllerTransitioningDelegate {

    init(...) {
        ...
        modalPresentationStyle = .Custom
        transitioningDelegate = self
    }

    public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return PopoverAnimatedTransitioning(forPresenting: true, position: position, fromView: fromView)
    }

    public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return PopoverAnimatedTransitioning(forPresenting: false, position: position, fromView: fromView)
    }

    public func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController?, sourceViewController source: UIViewController) -> UIPresentationController? {
        return PopoverPresentationController(presentedViewController: presented, presentingViewController: presenting, position: position, fromView: fromView)
    }

}

当我向控制器显示 presentViewController 并在 animated 属性 中传递 true 时,一切正常。但是当我想在没有动画的情况下呈现它并传递 false 时,UIKit 只调用 presentationControllerForPresentedViewController 方法,根本不调用 animationControllerForPresentedController 。就呈现的视图添加到视图层次结构并在动画转换对象中定位它而言,它从未创建,没有呈现。

我正在做的是检查演示控制器是否设置了动画过渡,如果不是,我手动创建动画过渡对象并将其设置为视图。

override public func presentationTransitionWillBegin() {
    ...
    if let transitionCoordinator = presentedViewController.transitionCoordinator() where !transitionCoordinator.isAnimated() {
        let transition = PopoverAnimatedTransitioning(forPresenting: true, position: position, fromView: fromView)
        transition.setupView(containerView!, presentedView: presentedView()!)
    }
}

可行,但我不确定这是否是最佳方法。

文档说表示控制器应该只负责在转换期间进行任何额外的设置或动画,并且表示的主要工作应该在动画转换对象中完成。

是否可以始终在呈现控制器中设置视图,而只在动画过渡对象中设置它们的动画?

有没有更好的方法来解决这个问题?

通过将视图设置的所有逻辑从动画转换移动到呈现控制器解决了这个问题。