简体   繁体   中英

How to programmatically show a window/view controller in Swift 4 for macOS application

I'm trying to programmatically show a window in my macOS application. The reason I want to do it programmatically is because the user clicks a Login button and the resulting function depends on the success of the login. If it was successful, the window is shown; otherwise, it is not.

Here is a screenshot of my Xcode window:

xcode窗口截图

Here's what I'm trying in the code ( Alert is a class I created to make showing NSAlert dialogs easier):

@IBAction func btnLogin_Click(_ sender: Any) {
    let email = txtEmail.stringValue
    if(email.isEmpty) {
        Alert.show(parent: view.window!, message: "Email is required.")
        return
    }

    let password = txtPassword.stringValue
    if(password.isEmpty) {
        Alert.show(parent: view.window!, message: "Password is required.")
        return
    }

    // this does not work, even though I gave the window and view controllers
    // both identifiers in the storyboard
    self.storyboard?.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("wcStores"))
}

Apple's documentation for NSStoryboard.SceneIdentifier is pretty much nonexistent, and other methods I've seen seem to pertain to earlier versions of Swift.

What am I doing wrong?

Alright, so this is not what I originally was trying to do, but this way is much better, and what I was really looking for.

let vcStores = self.storyboard?.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("vcStores"))
        as! NSViewController
self.view.window?.contentViewController = vcStores

This will just replace the window's contents with the contents in the view vcStores as defined in Interface Builder.

This video also helped, albeit for iOS and Swift 3. I was trying to create a new NSWindow at first because I'm so used to doing desktop development in Java Swing or C# Windows Forms. But I love how easy it is to just switch out the window contents like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM