gpt4 book ai didi

macos - 当应用程序位于最前面时显示 NSUserNotification 的横幅

转载 作者:搜寻专家 更新时间:2023-11-01 07:32:12 24 4
gpt4 key购买 nike

我想在应用程序显示在最前面时显示用户通知。我找到了下面的代码,但我不确定如何使用委托(delegate):它似乎只返回一个 bool 值。

class MyNotificationDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {

func applicationDidFinishLaunching(aNotification: NSNotification) {
NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self
}

func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool {
return true
} }

我试过一些句子,例如:

var delegate : MyNotificationDelegate = MyNotificationDelegate()
var notification:NSUserNotification = NSUserNotification()
var notificationcenter:NSUserNotificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter()

delegate.userNotificationCenter(notificationcenter, shouldPresentNotification: notification)

但它不会显示横幅。我知道对于 NSUserNotificationCenterdeliverNotification: 方法是显示横幅的方式。但我不确定 NSUserNotificationCenterDelegate 协议(protocol)。

如何始终显示通知横幅?

最佳答案

您的通知中心委托(delegate)和委托(delegate)方法应该在 AppDelegate 中实现,然后它才能工作。如果您在任何其他类中实现,它不会显示为横幅,尽管它会静静地出现在通知面板中。

我试过如下,它的工作:

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {



func applicationDidFinishLaunching(aNotification: NSNotification) {
let notification: MyNotificationDelegate = MyNotificationDelegate()
NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self;
notification.setNotification("Hi", message: "How are you?")
}

func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool {
return true
}

func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}


}

class MyNotificationDelegate: NSObject {

func setNotification(title: String, message: String)
{
let notification: NSUserNotification = NSUserNotification()
notification.title = title
notification.informativeText = message
NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification)
}
}

关于macos - 当应用程序位于最前面时显示 NSUserNotification 的横幅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31869040/

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