Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - UIView.transitionFromView -

What happens to your “fromView” after you use UIView.transitionFromView? How do you get it back? (re-initialize it?).

Here’s a simple example I made and get “fatal error: unexpectedly found nil while unwrapping an Optional value” when I try to get back to the “fromView” or reference a label on it, etc.

Let’s say I’ve set these views in my storyboard - I added a subview to the root called “cardView” and then 2 views under cardView called “backView” and “frontView"

Linked these up to the view controller and linked the Flip button to an action that looks like this (along with the variables):

@IBOutlet weak var backView: UIView!
@IBOutlet weak var frontView: UIView!
@IBOutlet var cardView: UIView!

var front = true

@IBAction func flipIt(sender: AnyObject) {
    if front {
        UIView.transitionFromView(self.frontView, toView: self.backView, duration: 1, options: UIViewAnimationOptions.TransitionFlipFromRight, completion: nil)
    } else {
        UIView.transitionFromView(self.backView, toView: self.frontView, duration: 1, options: UIViewAnimationOptions.TransitionFlipFromLeft, completion: nil)
    }
    front = !front
}

So when I run this - the first tap of the “Flip” button does fine, it flips over to the backView, but then when I tap it again I get “fatal error: unexpectedly found nil while unwrapping an Optional value” on the 2nd transitionFromView line (the one under “else”).

Obviously there’s some effect of transitionFromView that I don’t understand. I've tried a lot of different things, including a tutorial that uses this transition and was able to get it working but it doesn’t use the storyboard so I’m not sure how to apply how that tut does it to my storyboard views, apparently...

thanks for any help.

like image 419
Tommy Draughn Avatar asked May 17 '15 20:05

Tommy Draughn


1 Answers

You've declared your view properties as weak, so they're getting released as soon as it appears they're no longer needed. Just change them to strong (by removing "weak") and you should be golden:

@IBOutlet var backView: UIView!
@IBOutlet var frontView: UIView!
like image 185
Dave Batton Avatar answered Sep 21 '22 18:09

Dave Batton