当前位置 : 主页 > 手机开发 > 其它 >

cocoa – 在一定时间后隐藏NSUserNotification

来源:互联网 收集:自由互联 发布时间:2021-06-11
目前,当我使用警报样式创建NSUserNotification时,除非我手动关闭它,否则它将不会隐藏. 有没有办法可以在2秒后自动关闭/隐藏它? NSUserNotification代码仅供参考: let notification:NSUserNotificati
目前,当我使用警报样式创建NSUserNotification时,除非我手动关闭它,否则它将不会隐藏.

enter image description here

有没有办法可以在2秒后自动关闭/隐藏它?

NSUserNotification代码仅供参考:

let notification:NSUserNotification = NSUserNotification()
notification.title = "Title"
notification.subtitle = "Subtitle"
notification.informativeText = "Informative text"

notification.soundName = NSUserNotificationDefaultSoundName

notification.deliveryDate = NSDate(timeIntervalSinceNow: 10)
notification.hasActionButton = false
let notificationcenter:NSUserNotificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter()
notificationcenter.scheduleNotification(notification)
使用NSObject来实现这一点非常简单
performSelector:withObject:afterDelay:方法.

由于您在一定时间间隔后安排通知传递,因此您需要在解除之前将额外延迟添加到传递之前的初始延迟.在这里,我把它们写成交货前10秒的常数,以及解雇前2秒:

let delayBeforeDelivering: NSTimeInterval = 10
let delayBeforeDismissing: NSTimeInterval = 2

let notification = NSUserNotification()
notification.title = "Title"
notification.deliveryDate = NSDate(timeIntervalSinceNow: delayBeforeDelivering)

let notificationcenter = NSUserNotificationCenter.defaultUserNotificationCenter()

notificationcenter.scheduleNotification(notification)

notificationcenter.performSelector("removeDeliveredNotification:",
    withObject: notification,
    afterDelay: (delayBeforeDelivering + delayBeforeDismissing))
网友评论