gpt4 book ai didi

cocoa - 一定时间后隐藏 NSUserNotification

转载 作者:行者123 更新时间:2023-12-04 18:36:10 25 4
gpt4 key购买 nike

目前,当我使用 Alert 样式创建 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))

对于 Swift 5,您可以使用以下内容:
let delayBeforeDelivering: TimeInterval = 10
let delayBeforeDismissing: TimeInterval = 2

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

let notificationcenter = NSUserNotificationCenter.default

notificationcenter.scheduleNotification(notification)

notificationcenter.perform(#selector(NSUserNotificationCenter.removeDeliveredNotification(_:)),
with: notification,
afterDelay: (delayBeforeDelivering + delayBeforeDismissing))

关于cocoa - 一定时间后隐藏 NSUserNotification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34408343/

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