Server Programmer
Server Programmer

Reputation: 309

Navigate to New View Controller after Animation is Completed in Swift 3.0

I have (2) goals:

  1. Example #1: Navigate from the original View Controller to a new SecondViewController after the following animation is completed in Swift 3.0 (i.e. the User does not have to press any button and the App simply moves to the SecondViewController after the animation is completed)

  2. Example #2: Navigate from the original View Controller to a new SecondViewController after a time delay of 5 seconds in Swift 3.0 (i.e. the User does not have to press any button and the App simply moves to the SecondViewController after a timer reaches 5 seconds - no animation involved in the second example, just a timer)

Here is my code for Example #1:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    var imagesName = ["Image_1","Image_2","Image_3","Image_4","Image_5","Image_6","Image_7","Image_8","Image_9","Image_10","Image_11","Image_12","Image_13","Image_14","Image_15"]

    var images = [UIImage]()

    for i in 0..<imagesName.count{

        images.append(UIImage(named: imagesName[i])!)
    }

    imageView.animationImages = images
    imageView.animationDuration = 1.0
    imageView.startAnimating()

// Perhaps here is where we can fire the code to programatically move to a new View Controller after the animation is completed

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

Here is my Xcode setup:

enter image description here

Upvotes: 0

Views: 1635

Answers (1)

Kosuke Ogawa
Kosuke Ogawa

Reputation: 7451

Use DispatchQueue.main.asyncAfter.

EDITED

Set Storyboard ID to SecondViewController.

enter image description here

Example #1:

...
imageView.animationRepeatCount = 1 // <-- here
imageView.startAnimating()

DispatchQueue.main.asyncAfter(deadline: .now() + imageView.animationDuration) {
    let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController")
    self.show(secondViewController, sender: nil)
}

Example #2:

...
imageView.animationRepeatCount = 1 // <-- here
imageView.startAnimating()
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
    let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController")
    self.show(secondViewController, sender: nil)
}

Upvotes: 1

Related Questions