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

标签 macos swift delegates nsusernotificationcenter

我想在应用程序显示在最前面时显示用户通知。 我找到了下面的代码,但我不确定如何使用委托(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/

相关文章:

iphone - 在 View 之间连接委托(delegate)时出现问题

ios - 使用委托(delegate)从 VC2 取消隐藏 VC1 中的按钮

macos - 触控板手势切换到标题/源

macos - 在 OSX 10.8 上编程 F# 的最佳方式是什么?

Swift AVAudioPlayer (Xcode) - 在应用程序包外部播放音频文件

ios - 检测用户是否在 iOS 上滚动然后更改 View 颜色

ios 8 swift - 如何使用单独的数据源为 tableview 添加页脚

Swift - 以编程方式刷新约束

c# - 使用匿名方法调用 WPF Dispatcher

macos - OSX (XNU) 系统调用实际记录在哪里?