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

Dav*_*nte 5 cocoa nsalert swift 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)
        }
Run Code Online (Sandbox Code Playgroud)

但我收到了可怕的unexpectedly found nil while unwrapping an Optional value消息alert.beginSheetModal

请告诉我我做错了什么.

谢谢

Mic*_*lov 4

您应该运行您的代码,viewDidAppear因为您的视图控制器尚未在viewDidLoad.

override func viewDidAppear() {
    super.viewDidAppear()

    alertUser()
}
Run Code Online (Sandbox Code Playgroud)