Blinking Effect for NSTextField

This article explains how to create a nice blinking effect for a macOS Cocoa-based application with Swift 4.

I will skip the details how the countdown is implemented and focus on the blinking effect implementation.

Add a label object to your view and connect it to your IBOutlet:

@IBOutlet weak var timeLeftLabel: NSTextField!

Next, create and run the animation effect:

@objc func updateCountdown(timer: Timer!) {
    NSAnimationContext.runAnimationGroup({_ in
        NSAnimationContext.current.duration = 0.5
        timeLeftLabel.animator().alphaValue = 0.0  // Fade out
    }, completionHandler:{
        self.timeLeftLabel.animator().alphaValue = 1.0  // Fade in
    })
}

I'd like to explain why I'm setting NSAnimationContext.current.duration to half a second. I do so just because I'm running that blinking effect every second as a part of my countdown logic.

It's wrapped with:

Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.updateCountdown(timer:)), userInfo: "timer", repeats: true)  

The duration of 0.5 seconds doesn't allow a single second to be skipped and makes the effect look great.

Michael Samoylov

Python, JavaScript and Swift Expert with 12+ years of experience.

Vilnius, Lithuania https://monmar.tech

Subscribe to Michael Samoylov

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!