Search code examples
swiftanimationnsimagensstatusitemnsstatusbar

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


I'm new at Swift and I can't seem to find any resource for what I'm trying to achieve. Most of what I find applies only to views.

I have a statusBarItem:

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

Which has an NSImage as the icon:

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

And I'd like to animate the icon by making it pulse/fade in-out/animate opacity.

What's the best way of achieving this? 🤔

Thank you 🙏


Solution

  • Based on @Walt 's answer, I could figure out the macOS equivalent:

        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()
                }
            }
        }
    

    This will animate the button on a loop