2017-12-03 128 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窗體做桌面開發。但我喜歡這種切換窗口內容的容易程度。

相關問題