Fixing Keyboard shortcuts not working for TextFields in macOS apps

April 02, 20243 min read#swift, #macos

The problem

When working on Quick Drop app, I encounter a weird issue that all text fields inside my Preferences window don’t react to Cmd-V, Cmd-C command. This issue is not blocking users to enter text manually into the text fields, but it’s very unconvenient since one of the text field is for a lengthy activation key.

key

I posted this question on X and ask for help, but it doesn’t look like that other people are encountering it 🤔

The investigation

Quick Drop is a macOS app that use traditional AppKit’s AppDelegate lifecycle. But the preference window is built using Settings package and the content is built using SwiftUI. There are a lot of moving parts here.

Since I have never been a fan of Storyboard, I have followed this great tutorial to create Quick Drop app project without storyboard and nib files. During this process, I have deleted the Main.storyboard. It turns out that the it’s the main root cause of the issue.

By creating a completely new project to reproduce the issue, I can see that it’s important to have the main menu entry in the storyboard, and your app needs to load that main storyboard when starting, so that keyboard shortcuts can work on text fields in the app.

command

Further investigation, I found this Stack Overflow question from 14 years ago 😳.

It looks like that we can intercept the keyboard shortcuts and replicate the Cmd-V, Cmd-C functionality programatically, but it’d require a lot more code and also it’s not robust form my point of view

The solution

My solution for my app is to add back the Main.storyboard, but only keep the minimal entries to make the keyboard shortcuts working. I also deleted all extra default windows and view controllers in the original Main.storyboard file since my UI is created programatically. Keyboard shortcuts are working normally again on all my text fields.

final

Quick Drop logo

Profile picture

Personal blog by An Tran. I'm focusing on creating useful apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist


© An Tran - 2024