Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nil when unwrapping viewForKey(UITransitionContextFromViewKey) (Swift)

Tags:

swift

uiview

I am trying to do a custom transition animation. I have create an animation object that conforms to 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)

        }

    }

}

I am getting an error when trying to set the frame of fromView. It crashes on trying to force unwrap nil. What am I doing wrong here? Why is my fromView nil?

like image 324
Kex Avatar asked Mar 21 '16 04:03

Kex


2 Answers

This is the expected behavior:

If NO is returned from -shouldRemovePresentersView, the view associated with UITransitionContextFromViewKey is nil during presentation. This intended to be a hint that your animator should NOT be manipulating the presenting view controller's view. For a dismissal, the -presentedView is returned.

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

like image 167
Evgeniy Yurtaev Avatar answered Oct 11 '22 10:10

Evgeniy Yurtaev


Found the answer to this if anyone else is having this issue. I had myViewController.modalPresentationStyle = .Custom. For some reason this seems to be a bug and causes it to crash. Also the fromView controller isn't properly removed from the container view when transitionContext.completeTransition(true) is set. Just remove the custom presentation style line and it will work.

like image 25
Kex Avatar answered Oct 11 '22 11:10

Kex