Swiching between 2 diferent NSViewControllers with

2019-06-08 09:38发布

问题:

I'm absolute newbie in Swift and OSX development, and I'm sorry if my question will be too noob. I want to understand principles of navigation between NSViewControllers.

I have my default ViewController, where are login and password fields and button to login. After click on button, returns token. And now I trying to change "view" to SecondViewController and save somewhere token, I will need it in future. How can I do it? and it possible to do this in function?:

@IBAction func loginButton(_ sender: Any) {
   .... 
}

Thank you!

回答1:

You need to use segues to perform this action.

First make the segues connections between the ViewControllers using to storyboard editor. After that you need to give the segues an identifier on the storyboard's attributes inspector. Then in your code you can call the new ViewController by the segue like the code below.

With this code you can pass the data using the button:

class ViewController: NSViewController {

    var dataToPass: String = "DataToPass"

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func loginButton(_ sender: Any) {

        performSegue(withIdentifier: NSStoryboardSegue.Identifier(rawValue: "segueIdentifier"), sender: self)
    }

    override func prepare(for segue: NSStoryboardSegue, sender: Any?) {

        if segue.identifier!.rawValue == "segueIdentifier" {
            let destinationViewController = segue.destinationController as! ViewController2

            destinationViewController.dataToReceive = dataToPass
        }
    }
}


class ViewController2: NSViewController {

    var dataToReceive: String

    override func viewDidLoad() {
        super.viewDidLoad()

    }
}

And with this code you will use the override viewWillAppear

class ViewController: NSViewController {

    var dataToPass: String = "DataToPass"

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewWillAppear() {

        performSegue(withIdentifier: NSStoryboardSegue.Identifier(rawValue: "segueIdentifier"), sender: self)
    }

    override func prepare(for segue: NSStoryboardSegue, sender: Any?) {

        if segue.identifier!.rawValue == "segueIdentifier" {
            let destinationViewController = segue.destinationController as! ViewController2

            destinationViewController.dataToReceive = dataToPass
        }
    }
}


class ViewController2: NSViewController {

    var dataToReceive: String

    override func viewDidLoad() {
        super.viewDidLoad()

    }
}

In both cases you need to assure the data you want to pass to the other view controller is not null.