gpt4 book ai didi

cocoa - NSAlert - 如何将 View 呈现为工作表并在 Swift3 中获取返回值?

转载 作者:行者123 更新时间:2023-12-03 17:09:38 24 4
gpt4 key购买 nike

我有以下代码可以正常工作:

 func alertDialog(question: String, text: String) -> Bool {
let alert: NSAlert = NSAlert()
alert.messageText = question
alert.informativeText = text
alert.alertStyle = NSAlertStyle.warning
alert.addButton(withTitle: "Yes Please")
alert.addButton(withTitle: "No Thank You")
changedItem = false
return alert.runModal() == NSAlertFirstButtonReturn

我检查 NSAlertFirstButtonReturn 的值,如下所示:

 func tableViewSelectionDidChange(_ notification: Notification)
{
print (#function, "changedItem", changedItem!)
if changedItem == true {
let answer = alertDialog(question: "Save your changes?", text: "Unsaved changes will be shredded.")
print(#function, "answer: ", answer)
if answer == true {
print(#function, "TRUE")
saveChanges(self)
changedItem = false
}
}

我正在努力执行相同的功能,但将警报显示为表格。

我不知道如何呈现和测试结果。我目前的判断要么全对,要么全错。

我尝试了各种排列,如下所示,但没有任何乐趣,并且希望得到任何帮助。

//instead of the return sheetModal

var result: Int! = 0
//result = false
alert.beginSheetModal(for: self.view.window!, completionHandler: { (NSAlertFirstButtonReturn) -> Void in
if NSAlertFirstButtonReturn.hashValue == 1000 {
result = 1
} else {
result = 0
}


})
print(#function, "NSAlertFirstButtonReturn: ", NSAlertFirstButtonReturn.hashValue)
changedItem = false

if result == 1 {
return true
} else {
return false
}

最佳答案

runModal 方法不同,beginSheetModal(for:completionHandler:) 异步工作。不可能从包含异步任务的函数/方法返回值。

alertDialog 方法添加完成处理程序:

func alertDialog(question: String, text: String, completion: @escaping (Bool)->() ) {
let alert: NSAlert = NSAlert()
alert.messageText = question
alert.informativeText = text
alert.alertStyle = NSAlertStyle.warning
alert.addButton(withTitle: "Yes Please")
alert.addButton(withTitle: "No Thank You")
changedItem = false
alert.beginSheetModal(for: self.view.window!, completionHandler: { result in
completion(result == NSAlertFirstButtonReturn)
})
}

并使用方法:

func tableViewSelectionDidChange(_ notification: Notification)
{
print (#function, "changedItem", changedItem!)
if changedItem == true {
alertDialog(question: "Save your changes?", text: "Unsaved changes will be shredded.", completion: { [unowned self] answer in
print(#function, "answer: ", answer)
if answer == true {
print(#function, "TRUE")
self.saveChanges(self)
self.changedItem = false
}
})
}
}

功能实际上相同,但执行是异步的。

旁注:为什么 changedItem 是可选的?它似乎是一个真正的 Bool,只有两个状态。

关于cocoa - NSAlert - 如何将 View 呈现为工作表并在 Swift3 中获取返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42599225/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com