gpt4 book ai didi

swift - Hook 以退出应用程序事件并显示警报

转载 作者:可可西里 更新时间:2023-11-01 02:00:38 30 4
gpt4 key购买 nike

当用户通过单击 x 按钮退出应用程序时,我需要显示一个警告框。我如何 Hook 到应用程序的退出事件并通过以下方式显示警告或 View Controller 一个 segue

performSegue(withIdentifier: "segue", sender: nil)

请指教..

最佳答案

我知道您想使用 segue 来执行此操作,因为它们非常方便,但是无法在 Storyboard中从应用程序委托(delegate)事件(如“applicationWillResignActive”(继续背景)或“applicationWillBecomeActive”(再次成为前台)。

执行此操作的正确方法是通过警报。并且您可能希望在 applicationShouldTerminate 中执行此操作,因为您可能希望 A) 如果您有充分的理由暂时不退出,则能够中止退出或 B) 给用户一个选择是否真的戒掉。

这是它在 swift 4 中的样子:

var licenseWindowController : LicenseWindowController?

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
}

func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {

let answer = dialogOKCancel(question: "Ok?", text: "Should we really quit?")
if answer == true
{
return .terminateNow
} else {

func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {

let answer = dialogOKCancel(question: "Ok?", text: "Should we really quit?")
if answer == true
{

return .terminateNow

} else {

// to bring up a window from your storyboard...
let mainStoryboard = NSStoryboard.init(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil)
self.licenseWindowController = mainStoryboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "LicenseWindowController")) as? LicenseWindowController
if let actualLicenseWC = self.licenseWindowController
{
actualLicenseWC.showWindow(self)
}

return .terminateCancel
}
}

swift 3

var licenseWindowController : LicenseWindowController?

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() == NSAlertFirstButtonReturn
}

func applicationShouldTerminate(_ sender: NSApplication) -> NSApplicationTerminateReply {

let answer = dialogOKCancel(question: "Ok?", text: "Should we really quit?")
if answer == true
{
return .terminateNow
} else {
let mainStoryboard = NSStoryboard.init(name: "Main", bundle: nil)
self.licenseWindowController = mainStoryboard.instantiateController(withIdentifier: "LicenseWindowController") as? LicenseWindowController
if let actualLicenseWC = self.licenseWindowController
{
actualLicenseWC.showWindow(self)
}

return .terminateCancel
}
}

关于swift - Hook 以退出应用程序事件并显示警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46628610/

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