Swift - 如何使菜单栏中的 NSImage 具有动画效果(在不透明度 0 和 1 之间波动)?

Swift - How does one animate (pulse between opacity 0 and 1) a NSImage in the menu bar?

我是 Swift 的新人,我似乎找不到任何资源来实现我想要实现的目标。我发现的大部分内容仅适用于视图。

我有一个 statusBarItem:

statusBarItem = NSStatusBar.system.statusItem(withLength: CGFloat(NSStatusItem.variableLength))

其中有一个 NSImage 作为图标:

let img = NSImage(named: "\(appModel.selectedImage.rawValue)")
img?.size = CGSize(width: 22, height: 22)
statusBarItem.button?.image = img

我想通过 pulse/fade in-out/animate 不透明度来为图标设置动画。

实现此目标的最佳方法是什么?

谢谢

查看 class 层次结构以了解您要实现的目标。 NSStatusBar 是一个 NSObject,并且不知道如何呈现。它有一个 NSStatusBarButton,它可以。没试过,但有点像

UIView.animateWithDuration(0.2, delay:0, options: [.repeat], animations: {
    statusBarItem.button.opacity = 0
}, completion: {
    (value: Bool) in
statusBarItem.button.opacity = 1
})

根据@Walt 的回答,我可以找出 macOS 等效项:

    func animateMenubarIcon() {
        NSAnimationContext.runAnimationGroup { context in
            context.duration = 1
            self.statusBarItem?.button?.animator().alphaValue = 0
        } completionHandler: {
            NSAnimationContext.runAnimationGroup { context in
                context.duration = 1
                self.statusBarItem?.button?.animator().alphaValue = 1
            } completionHandler: {
                self.animateMenubarIcon()
            }
        }
    }

这将使按钮循环播放