Jeamz
Jeamz

Reputation: 21

How to programmatically add a second view in swift 3

Im trying to switch to a second view from a button on the first view, and do this programmatically (not using the traditional way of switching between views using a segue on the storyboard)

My current app delegate:

import UIKit

@UIApplicationMain
public class AppDelegate: UIResponder, UIApplicationDelegate {

    public var window: UIWindow?

    public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        window = UIWindow(frame: UIScreen.main.bounds)
        window?.makeKeyAndVisible()
        window?.rootViewController = UINavigationController(rootViewController: ViewController())

        return true
    }

Button function in first view controller that when pressed should just switch to new view:

func signupAction (sender: UIButton!){

}

I already have the new viewcontroller file created:

class Signup: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.cyan
    }
}

Basically, I'm trying to achieve the button in the first viewcontroller transitions to this signup viewcontroller.

Upvotes: 1

Views: 555

Answers (1)

Mo Abdul-Hameed
Mo Abdul-Hameed

Reputation: 6110

If you are in a UINavigationController you could push the Signup view controller to the navigation stack this way:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let signUpViewController = storyboard.instantiateViewController(withIdentifier: "signUpViewController") as! Signup
navigationController?.pushViewController(signUpViewController, animated: true)

If you are not in UINavigationController and want to present it, you can do it this way:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let signUpViewController = storyboard.instantiateViewController(withIdentifier: "signUpViewController") as! Signup
self.present(signUpViewController, animated: true, completion: nil)

Note: Don't forget to set the identifier of your view controller in the storyboard.

Upvotes: 1

Related Questions