Loading...

How to detect fn key press in Swift?

question macOS swift
Ram Patra Published on November 10, 2021
Swift 5.0+

You can override the flagsChanged() method of NSViewController and have your code like below to detect fn key press and release in macOS:

override func flagsChanged(with event: NSEvent) {
	if event.modifierFlags.intersection(.deviceIndependentFlagsMask).contains(.function) {
		print("fn key pressed")
	}
        
	if event.modifierFlags.intersection(.deviceIndependentFlagsMask) == [] {
		print("fn key released")
	}
}

P.S. The above solution was derived from this answer on SOF. This solution would also work for any of the modifier keys like Cmd, Shift, Opt, etc. However, note that this would be triggered even if a user has the fn key pressed all the time but presses/releases any other modifier keys. The above code doesn’t exactly detect fn key presses but rather whether the fn key is present in the list of modifier keys being pressed/released.

Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on November 10, 2021
Image placeholder

Keep reading

If this article was helpful, others might be too

question swift macOS October 29, 2023 How to make Color conform to RawRepresentable in SwiftUI in macOS?

For various reasons you may want to convert the Color type to a String. And, below is a relatively cleaner way to do it.

May 28, 2020 Best Mac Apps for Working From Home

For me personally, it is a mixed feeling working from home. On one hand, I have the flexibility with when to work and when not to but on the other hand, it is sometimes hard for me to find that fine line between work and life. There are days when I keep working even after office hours without realizing that I have got my life wife too :)

question swiftui swift February 19, 2025 How to change the window level to floating, popUpMenu, etc. in SwiftUI?

When developing macOS applications with SwiftUI, you might need to create floating windows that stay on top of other windows. While modern macOS versions (15+) make this straightforward with the .windowLevel(.floating) modifier, supporting older versions requires a different approach. In this post, I’ll show you how to create floating windows that work across different macOS versions.

Like my work?

Please, feel free to reach out. I would be more than happy to chat.