2017-12-03 127 views
0

我试图以编程方式在我的macOS应用程序中显示一个窗口。我想以编程方式执行此操作的原因是因为用户单击登录按钮,并且生成的功能取决于登录成功。如果成功,则显示窗口;否则,它不是。如何以编程方式在Swift 4中显示窗口/视图控制器for macOS应用程序

这里是我的Xcode窗口截图:

xcode window screenshot

这里就是我想要的代码(Alert是一类我创建使显示NSAlert对话更容易):

@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")) 
} 

NSStoryboard.SceneIdentifier的Apple文档几乎不存在,其他我见过的方法似乎与早期版本的Swift有关。

我在做什么错?

+0

您只设置了一个标识符。并且你没有实例化NSWindowController。 –

+0

@ElTomato感谢您的评论,Swift和Mac开发新手都很适合我。我添加了自己的答案,因为我终于想出了如何去做我真正想做的事情。 –

+0

如果您对您的解决方案感到满意,那么也可以随我一起找到。我不会回答它,但我会试着找出为什么NSWindowController首先连接到主视图控制器,如果我是你的话。 –

回答

0

好吧,所以这不是我最初试图做的事情,但这种方式更好,我真正在寻找的东西。

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

这将只是在视图vcStores在接口生成器中定义的内容替换窗口内容。

This video也有帮助,虽然iOS和斯威夫特3.我是想先创建一个新的NSWindow,因为我已经习惯在Java Swing或C#Windows窗体做桌面开发。但我喜欢这种切换窗口内容的容易程度。

相关问题