【问题标题】:Create an NSAlert with Swift使用 Swift 创建 NSAlert
【发布时间】:2015-06-08 14:53:12
【问题描述】:

我有在 Objective-C 中创建和 NSAlert 的代码,但我现在想在 Swift 中创建它。

警报是为了确认用户想要删除文档。

我希望“删除”按钮运行删除功能,而“取消”按钮只是为了解除警报。

我怎样才能用 Swift 写这个?

NSAlert *alert = [[[NSAlert alloc] init] autorelease];
[alert addButtonWithTitle:@"Delete"];
[alert addButtonWithTitle:@"Cancel"];
[alert setMessageText:@"Delete the document?"];
[alert setInformativeText:@"Are you sure you would like to delete the document?"];
[alert setAlertStyle:NSWarningAlertStyle];
[alert beginSheetModalForWindow:[self window] modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];

【问题讨论】:

  • 您可能想考虑beginSheetModal(for:completionHandler:) 已被弃用,实际上它可能是处理模态对话框(在一个块中)的更理想的方式。它也更接近于 didEndSelector 的旧方式,并且不会停止整个应用程序。

标签: swift cocoa nsalert


【解决方案1】:

beginSheetModalForWindow:modalDelegate 在 OS X 10.10 Yosemite 中已弃用。

斯威夫特 2

func dialogOKCancel(question: String, text: String) -> Bool {
    let alert: NSAlert = NSAlert()
    alert.messageText = question
    alert.informativeText = text
    alert.alertStyle = NSAlertStyle.WarningAlertStyle
    alert.addButtonWithTitle("OK")
    alert.addButtonWithTitle("Cancel")
    let res = alert.runModal()
    if res == NSAlertFirstButtonReturn {
        return true
    }
    return false
}

let answer = dialogOKCancel("Ok?", text: "Choose your answer.")

这将根据用户的选择返回truefalse

NSAlertFirstButtonReturn 代表添加到对话框的第一个按钮,这里是“确定”按钮。

斯威夫特 3

func dialogOKCancel(question: String, text: String) -> Bool {
    let alert = NSAlert()
    alert.messageText = question
    alert.informativeText = text
    alert.alertStyle = NSAlertStyle.warning
    alert.addButton(withTitle: "OK")
    alert.addButton(withTitle: "Cancel")
    return alert.runModal() == NSAlertFirstButtonReturn
}

let answer = dialogOKCancel(question: "Ok?", text: "Choose your answer.")

斯威夫特 4

我们现在使用枚举作为警报的样式按钮选择。

func dialogOKCancel(question: String, text: String) -> Bool {
    let alert = NSAlert()
    alert.messageText = question
    alert.informativeText = text
    alert.alertStyle = .warning
    alert.addButton(withTitle: "OK")
    alert.addButton(withTitle: "Cancel")
    return alert.runModal() == .alertFirstButtonReturn
}

let answer = dialogOKCancel(question: "Ok?", text: "Choose your answer.")

【讨论】:

  • 确保import AppKit(至少在swift 3中)
  • @Claude 如果您发出警报,则意味着您正在制作一个 Cocoa 应用程序,这意味着您正在导入已经导入 AppKit 的 Cocoa。
  • 可能我不应该从非 VC 类触发警报;但我只是想要一些穷人的错误显示。这个 util 类除了 Foundation 没有导入任何东西,所以我需要导入(至少它让 XCode 高兴)。
  • @Claude 哦,我明白了。在这种情况下,您手动导入 AppKit 是正确的 - 很抱歉造成混淆。
  • alert.alertStyle = .warning 也适用于 Swift 3,无需添加 NSAlertStyle
【解决方案2】:

我认为这可能对你有用...

let a = NSAlert()
a.messageText = "Delete the document?"
a.informativeText = "Are you sure you would like to delete the document?"
a.addButtonWithTitle("Delete")
a.addButtonWithTitle("Cancel")
a.alertStyle = NSAlert.Style.WarningAlertStyle

a.beginSheetModalForWindow(self.view.window!, completionHandler: { (modalResponse) -> Void in
    if modalResponse == NSAlertFirstButtonReturn {
        print("Document deleted")
    }
})

【讨论】:

  • NSAlert.Style.WarningAlertStyle 你需要在NSAlertStyle 之间有一个句点
【解决方案3】:

更新了 Jose Hidalgo 对 Swift 4 的回答:

let a: NSAlert = NSAlert()
a.messageText = "Delete the document?"
a.informativeText = "Are you sure you would like to delete the document?"
a.addButton(withTitle: "Delete")
a.addButton(withTitle: "Cancel")
a.alertStyle = NSAlert.Style.warning

a.beginSheetModal(for: self.window!, completionHandler: { (modalResponse: NSApplication.ModalResponse) -> Void in
    if(modalResponse == NSApplication.ModalResponse.alertFirstButtonReturn){
        print("Document deleted")
    }
})

【讨论】:

    【解决方案4】:

    选择@Jose Hidalgo 对 Swift 5 的回答

            let a = NSAlert()
            a.messageText = "Delete the document?"
            a.informativeText = "Are you sure you would like to delete the document?"
            //   .alertFirstButtonReturn
            a.addButton(withTitle: "Delete")
    
            //   .alertSecondButtonReturn
            a.addButton(withTitle: "Cancel")
            a.alertStyle = .warning
            var w: NSWindow?
            if let window = view.window{
                w = window
            }
            else if let window = NSApplication.shared.windows.first{
                w = window
            }
            if let window = w{
                a.beginSheetModal(for: window){ (modalResponse) in
                    if modalResponse == .alertFirstButtonReturn {
                        print("Document deleted")
                    }
                }
            }
    

    【讨论】:

    • 在这里使用 nil 合并运算符会更漂亮,如下所示: if let window = view.window ?? NSApplication.shared.windows.first { alert.beginSheetModal(for: window) }
    • 视图未定义?
    • 是的,代码在NSViewController
    【解决方案5】:

    我尝试了上述解决方案,但无法获得适当大小的警报。我也定义了警报的大小。

            let alert = NSAlert()
            alert.messageText = "YOUR MESSAGE"
            alert.addButton(withTitle: "BUTTON1")
            alert.addButton(withTitle: "BUTTON2")
            var frame = alert.window.frame
            frame.size.height = 300
            frame.size.width = 200
            alert.window.setFrame(frame, display: true)
            
            let stackViewer = NSStackView(frame: NSRect(x: 0, y: 0, width: 200, height: 00))
            alert.accessoryView = stackViewer
            
            
            alert.beginSheetModal(for: self.view.window!, completionHandler: { (modalResponse) -> Void in
                    if modalResponse == NSApplication.ModalResponse.alertFirstButtonReturn {
                        print("first btn")
                        
                    }else{
                        print("second btn")
                  
                }
            })
    

    【讨论】:

      猜你喜欢
      • 2012-01-06
      • 2010-10-20
      • 2014-06-08
      • 2010-12-05
      • 2017-01-18
      • 2018-08-10
      • 2014-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多