解包viewForKey(UITransitionContextFromViewKey)时的Nil(Swift)

时间:2016-03-21 04:34:12

标签: swift uiview

我正在尝试自定义过渡动画。我创建了一个符合UIViewControllerAnimatedTransitioning的动画对象:

import UIKit

class ViewControllerAnimator: NSObject, UIViewControllerAnimatedTransitioning {

    let duration = 1.0

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

    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {

        let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!

        //Animate out
        UIView.animateWithDuration(duration, animations: { () -> Void in
            fromView.frame.origin.x -= 200
            }) { (Bool) -> Void in
                transitionContext.completeTransition(true)

        }

    }

}

尝试设置fromView的框架时出错。它试图强行解开零时崩溃。我在这做错了什么?为什么我的fromView nil?

2 个答案:

答案 0 :(得分:17)

如果有其他人遇到此问题,请找到答案。我有myViewController.modalPresentationStyle = .Custom。出于某种原因,这似乎是一个错误,并导致它崩溃。当设置transitionContext.completeTransition(true)时,也无法从容器视图中正确删除fromView控制器。只需删除自定义演示文稿样式行即可。

答案 1 :(得分:3)

这是预期的行为:

  

如果从-shouldRemovePresentersView返回NO,则视图   与UITransitionContextFromViewKey关联的是nil期间   介绍。这意味着你的动画师应该提示   不要操纵呈现视图控制器的视图。为一个   解雇后,会返回-sentsentView。

https://developer.apple.com/library/content/samplecode/CustomTransitions/Listings/CustomTransitions_Custom_Presentation_AAPLCustomPresentationController_m.html