Maximilian Krause
Maximilian Krause

Reputation: 1155

Custom Segue animates into black before displaying destination view controller

I'm using a custom segue in order to transition between two view controllers. This is the segue I'm using for one of those transitions:

class SegueFromRight: UIStoryboardSegue{
    override func perform() {
        // Assign the source and destination views to local variables.
        let src = self.source.view as UIView!
        let dst = self.destination.view as UIView!

        // Get the screen width and height.
        let screenWidth = UIScreen.main.bounds.size.width
        let screenHeight = UIScreen.main.bounds.size.height

        // Specify the initial position of the destination view.
        dst?.frame = CGRect(0.0, screenHeight, screenWidth, screenHeight)

        // Access the app's key window and insert the destination view above the current (source) one.
        let window = UIApplication.shared.keyWindow
        window?.insertSubview(dst!, aboveSubview: src!)

        // Animate the transition.
        UIView.animate(withDuration: 0.4, animations: { () -> Void in
            src?.frame = (src?.frame.offsetBy(dx: -screenWidth, dy: 0.0))!
            dst?.frame = (dst?.frame.offsetBy(dx: -screenWidth, dy: 0.0))!

        }) { (Finished) -> Void in
            self.source.present(self.destination as UIViewController,
                                                            animated: false,
                                                            completion: nil)
        }

    }
}

The segue works perfectly, however the animation is not how I'd like it. When it "pushes" the destination view controller, it's shown black. It only turns to the actual view controller as soon as the animation is finished. I guess that's because the new view controller is only loaded once the animation is finished. But how would I go about preloading the new view controller, so that the animation looks smooth? The unwinding segue does not display that black animation, as the destination view controller (the previous source view controller) is already loaded of course.

Upvotes: 0

Views: 240

Answers (1)

theMikeSwan
theMikeSwan

Reputation: 4729

This is likely your problem dst?.frame = CGRect(0.0, screenHeight, screenWidth, screenHeight).

Try this instead dst?.frame = CGRect(screenWidth, 0.0, screenWidth, screenHeight).

Your original line sets the destination view to be off the bottom of the screen rather than off to the right edge of the screen. When you animate the views by the screen width the destination slides from directly below the screen to below and to the left.

Upvotes: 0

Related Questions