Swift 3, Xcode 8 Instantiate View Controller Is Not Working

Swift 3, Xcode 8 Instantiate View Controller is not working

Try like this.

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

XCTestCase error when instantiate view controller from storyboard

After struggling for two days, i finally found the root problem.

The problem is cast issue, there are two module with the same name which is appName in my case. This make xCode confused, which is why it cannot cast the view controller.

Since module name usually take product name as its source, i change the test product name and my problem finally solved.

Instantiate and Present a viewController in Swift

This answer was last revised for Swift 5.4 and iOS 14.5 SDK.


It's all a matter of new syntax and slightly revised APIs. The underlying functionality of UIKit hasn't changed. This is true for a vast majority of iOS SDK frameworks.

let storyboard = UIStoryboard(name: "myStoryboardName", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "myVCID")
self.present(vc, animated: true)

Make sure to set myVCID inside the storyboard, under "Storyboard ID."

Sample Image

Swift 3 / Xcode 8.2 - switch view in viewDidLoad not working

Remove the code from viewDidLoad method and use the below method.

 override func viewDidAppear() {
guard let user = UserDefaults.standard.string(forKey: "loginSuccessfull"), user == "true" else {
return
}
let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondView")!
self.present(vc, animated: true)
}


Related Topics



Leave a reply



Submit