如何在最新的swift中编写NSAlert?

时间:2016-09-10 14:34:57

标签: swift cocoa nsalert macos-sierra

我试图写下此提醒:

func alertUser() {
        let alert = NSAlert()
        alert.messageText = "message 1"
        alert.informativeText = "info1"
        alert.informativeText = "info2"
        alert.addButton(withTitle: "NO")
        alert.addButton(withTitle: "YES")
        alert.beginSheetModal(for: self.view.window!) { (returnCode: NSModalResponse) -> Void in
            print ("returnCode: ", returnCode)
        }

但是我在第unexpectedly found nil while unwrapping an Optional value

上收到了可怕的alert.beginSheetModal消息

请告诉我我做错了什么。

由于

1 个答案:

答案 0 :(得分:4)

您应该从viewDidAppear运行代码,因为您的视图控制器尚未在viewDidLoad中创建窗口对象。

override func viewDidAppear() {
    super.viewDidAppear()

    alertUser()
}