Aleric Aleric - 1 month ago 126
Swift Question

Swift 3, Xcode 8 Instantiate View Controller is not working

Xcode 8 when it compiles says to change instantiate

viewcontroller
with identifier to simply, instantiate view controller. I did that, why does it give two errors?

I'm working with Swift 3. I want to change pages programmatically.I've read a lot of other questions on the topic. All of them use instantiate view controller with the identifier. They haven't adopted the new language.

@IBAction func switchPage(_ sender: UIButton) {

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController =
storyboard.instantiateViewController("secondViewController") as!
UIViewController
self.presentViewController(secondViewController, animated: true,
completion: nil)

}


Thanks. I changed the code as suggested, and receive only one error: Value of optional type 'UIStoryboard?' not unwrapped; did you mean to use '!' or '?'? Should I add an exclamation point somewhere?

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a
nib.
}

@IBAction func ch(_ sender: UIButton) {



let viewController =
storyboard.instantiateViewController(withIdentifier:
"secondViewController") as! UIViewController
self.present(viewController, animated: true)



}




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



}

Answer

Try like this.

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier :"secondViewController") as! UIViewController
self.present(viewController, animated: true)