Reputation: 883
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:
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?
Upvotes: 2
Views: 5700
Reputation: 31
Use these two function to go to the target NSViewcontroller/UIViewcontroller: (you must assign a unique storyboard id to the target view controller)
Mac APP:
public func gotToNextVc(_ viewControllerIdentifier: String) {
let nextVC = self.storyboard?.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(viewControllerIdentifier))
as! NSViewController
self.view.window?.contentViewController = nextVC
}
IOS APP:
public func gotToNextVc(_ viewControllerIdentifier: String){
let storyBoard = UIStoryboard(name: ViewControllers.STORYBOARD, bundle: nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: viewControllerIdentifier)
view.endEditing(true)
nextViewController.modalPresentationStyle = .fullScreen
nextViewController.modalTransitionStyle = .coverVertical
self.present(nextViewController, animated: false, completion: nil)
}
Upvotes: 0
Reputation: 883
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.
Upvotes: 5