1

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

Maxime Dupré
  • 5,319
  • 7
  • 38
  • 72

2 Answers2

0

Look at the class hierarchy for what you're trying to achieve. A NSStatusBar is a NSObject, and does not know how to render. It has a NSStatusBarButton, which does. Haven't tried, but something like

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

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

Maxime Dupré
  • 5,319
  • 7
  • 38
  • 72