惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Hacker News: Ask HN
Hacker News: Ask HN
N
News and Events Feed by Topic
Forbes - Security
Forbes - Security
The Last Watchdog
The Last Watchdog
TaoSecurity Blog
TaoSecurity Blog
Schneier on Security
Schneier on Security
SecWiki News
SecWiki News
V
Vulnerabilities – Threatpost
Project Zero
Project Zero
O
OpenAI News
W
WeLiveSecurity
Security Archives - TechRepublic
Security Archives - TechRepublic
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
H
Hacker News: Front Page
Cisco Talos Blog
Cisco Talos Blog
Spread Privacy
Spread Privacy
Help Net Security
Help Net Security
P
Privacy & Cybersecurity Law Blog
K
Kaspersky official blog
S
Security @ Cisco Blogs
Latest news
Latest news
AWS News Blog
AWS News Blog
U
Unit 42
Martin Fowler
Martin Fowler
阮一峰的网络日志
阮一峰的网络日志
S
Secure Thoughts
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Know Your Adversary
Know Your Adversary
Scott Helme
Scott Helme
博客园 - 司徒正美
B
Blog RSS Feed
C
Check Point Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
D
Docker
Google Online Security Blog
Google Online Security Blog
Jina AI
Jina AI
aimingoo的专栏
aimingoo的专栏
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Last Week in AI
Last Week in AI
月光博客
月光博客
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
SegmentFault 最新的问题
NISL@THU
NISL@THU
T
The Blog of Author Tim Ferriss
C
Cisco Blogs
Attack and Defense Labs
Attack and Defense Labs
小众软件
小众软件

Peter Steinberger

OpenClaw, OpenAI and the future | Peter Steinberger Shipping at Inference-Speed | Peter Steinberger The Signature Flicker | Peter Steinberger Just Talk To It - the no-bs Way of Agentic Engineering | Peter Steinberger Claude Code Anonymous | Peter Steinberger Live Coding Session: Building Arena | Peter Steinberger My Current AI Dev Workflow | Peter Steinberger Essential Reading for Agentic Engineers - August 2025 | Peter Steinberger Just One More Prompt | Peter Steinberger Poltergeist: The Ghost That Keeps Your Builds Fresh | Peter Steinberger Don't read this Startup Slop | Peter Steinberger Essential Reading for Agentic Engineers - July 2025 | Peter Steinberger Self-Hosting AI Models After Claude's Usage Limits | Peter Steinberger Logging Privacy Shenanigans | Peter Steinberger VibeTunnel's first AI-anniversary | Peter Steinberger Making AppleScript Work in macOS CLI Tools: The Undocumented Parts | Peter Steinberger Peekaboo 2.0 – Free the CLI from its MCP shackles | Peter Steinberger Command your Claude Code Army, Reloaded | Peter Steinberger Essential Reading for Agentic Engineers | Peter Steinberger Slot Machines for Programmers: How Peter Builds Apps 20x Faster with AI | Peter Steinberger My AI Workflow for Understanding Any Codebase | Peter Steinberger stats.store: Privacy-First Sparkle Analytics | Peter Steinberger Showing Settings from macOS Menu Bar Items: A 5-Hour Journey | Peter Steinberger VibeTunnel: Turn Any Browser into Your Mac's Terminal | Peter Steinberger Vibe Meter 2.0: Calculating Claude Code Usage with Token Counting | Peter Steinberger llm.codes: Make Apple Docs AI-Readable | Peter Steinberger Automatic Observation Tracking in UIKit and AppKit: The Feature Apple Forgot to Mention | Peter Steinberger Peekaboo MCP – lightning-fast macOS screenshots for AI agents | Peter Steinberger Migrating 700+ Tests to Swift Testing: A Real-World Experience | Peter Steinberger Commanding Your Claude Code Army | Peter Steinberger Code Signing and Notarization: Sparkle and Tears | Peter Steinberger Vibe Meter: Monitor Your AI Costs | Peter Steinberger Claude Code is My Computer | Peter Steinberger Stop Over-thinking AI Subscriptions | Peter Steinberger Introducing Demark: HTML in. MD out. Blink-fast. | Peter Steinberger The Future of Vibe Coding: Building with AI, Live and Unfiltered | Peter Steinberger MCP Best Practices | Peter Steinberger Finding My Spark Again | Peter Steinberger Top-Level Menu Visibility in SwiftUI for macOS | Peter Steinberger Supporting Both Tap and Long Press on a Button in SwiftUI | Peter Steinberger On Using Apple Silicon Mac Mini for Continuous Integration | Peter Steinberger Apple Silicon M1: A Developer's Perspective | Peter Steinberger Gardening Your Twitter: Curating Your Timeline | Peter Steinberger Gardening Your Twitter: Growing Your Followers | Peter Steinberger Forbidden Controls in Catalyst: Optimize Interface for Mac | Peter Steinberger Disabling Keyboard Avoidance in SwiftUI's UIHostingController | Peter Steinberger The State of SwiftUI | Peter Steinberger Logging in Swift | Peter Steinberger Building with Swift Trunk Development Snapshots | Peter Steinberger Calling Super at Runtime in Swift | Peter Steinberger zld — A Faster Version of Apple's Linker | Peter Steinberger How to Fix LLDB: Couldn't IRGen Expression | Peter Steinberger Updating macOS on a Hackintosh | Peter Steinberger InterposeKit — Elegant Swizzling in Swift | Peter Steinberger The Great Mac Catalyst Text Input Crash Hunt | Peter Steinberger Jailbreaking for iOS Developers | Peter Steinberger Network Kernel Core Dump | Peter Steinberger How to macOS Core Dump | Peter Steinberger Kernel Panics and Surprise boot-args | Peter Steinberger The LG UltraFine 5K, kernel_task, and Me | Peter Steinberger Let's Try This Again | Peter Steinberger How We Work at PSPDFKit | Peter Steinberger Swizzling in Swift | Peter Steinberger WWDC for First-Timers, 2019 Edition | Peter Steinberger Challenges of Adopting Drag and Drop | Peter Steinberger Marzipan: Porting iOS Apps to the Mac | Peter Steinberger How to Use Slack and Not Go Crazy | Peter Steinberger Hardcore Debugging - Heavy Weapons for Hard Bugs | Peter Steinberger Binary Frameworks in Swift | Peter Steinberger Even Swiftier Objective-C | Peter Steinberger The Case for Deprecating UITableView | Peter Steinberger Running tests with Clang Address Sanitizer | Peter Steinberger UI testing on iOS, without busy waiting | Peter Steinberger Hiring a distributed team | Peter Steinberger Writing Good Bug Reports | Peter Steinberger Real-time collaboration, Apple, and you | Peter Steinberger Converting Xcode Test Runs to JUnit, the Fast Way | Peter Steinberger Efficient iOS Version Checking | Peter Steinberger Investigating Thread Safety of UIImage | Peter Steinberger Swifty Objective-C | Peter Steinberger Running UI Tests on iOS With Ludicrous Speed | Peter Steinberger A Pragmatic Approach to Cross-Platform | Peter Steinberger Surprises with Swift Extensions | Peter Steinberger Using ccache for Fun and Profit | Peter Steinberger UITableViewController designated initializer woes | Peter Steinberger Researching ResearchKit | Peter Steinberger The curious case of rotation with multiple windows on iOS 8 | Peter Steinberger UIKit Debug Mode | Peter Steinberger Retrofitting containsString: on iOS 7 | Peter Steinberger A Story About Swizzling "the Right Way™" and Touch Forwarding | Peter Steinberger Hacking with Aspects | Peter Steinberger Fixing UITextView On iOS 7 | Peter Steinberger Fixing What Apple Doesn't | Peter Steinberger How To Inspect The View Hierarchy Of Third-Party Apps | Peter Steinberger Fixing UISearchDisplayController On iOS 7 | Peter Steinberger Smart Proxy Delegation | Peter Steinberger Adding Keyboard Shortcuts To UIAlertView | Peter Steinberger How To Center Content Within UIScrollView | Peter Steinberger UIAppearance for Custom Views | Peter Steinberger Hacking Block Support Into UIMenuItem | Peter Steinberger
Fixing keyboardShortcut in SwiftUI | Peter Steinberger
Peter Steinberger · 2021-01-31 · via Peter Steinberger

iOS 14 introduced keyboardShortcut, a convenient native way to add keyboard shortcuts to SwiftUI. However, if you end up using it, it likely won’t work. I was curious why that is, so follow along with me for a round of SwiftUI debugging! Spoiler: The workaround is at the end of this article.

Behavior Inventory

Let’s first check out how this feature works:

struct ContentView: View {
    var body: some View {
        Button("Keyboard Enabled Button") {
            print("P pressed")
        }.keyboardShortcut("p", modifiers: [.command])
    }
}

Simple enough. However, when I tried, it didn’t work in production. After simplifying my setup and eventually writing my own example project, I eventually realized my code is correct and this just doesn’t work.

But surely Apple tested this? Let’s try a few combinations:

  • UIKit app lifecycle, iOS 14: ❌
  • UIKit app lifecycle, Catalyst Big Sur: ✅1
  • SwiftUI app lifecycle, iOS 14: ✅
  • SwiftUI app lifecycle, Catalyst Big Sur: ✅

Right. So things work pretty much everywhere, but not in the use case that will likely be the most common one: when mixing SwiftUI and UIKit.

The Solution

I’ve been discussing this on Twitter and was quickly given a workaround (thanks Mateus!) to try:

let host = UIHostingController(rootView: SwiftUIView())

// Workaround for `keyboardShortcut` not working:
let window = UIWindow()
window.rootViewController = host
window.makeKeyAndVisible()

present(host, animated: true, completion: nil)

And sure enough — this indeed does the trick! But it got me even more curious. Mateus talks about a keyboardShortcutBridge in UIHostingController that takes care of keyboard management. Let’s see if we can verify that in LLDB:

Printing description of host:
<_TtGC7SwiftUI19UIHostingControllerV15SwiftUIKeyboard11SwiftUIView_: 0x7fc4f4408360>
(lldb) expression -l objc -O -- [0x7fc4f4408360 _ivarDescription]
<_TtGC7SwiftUI19UIHostingControllerV15SwiftUIKeyboard11SwiftUIView_: 0x7fc4f4408360>:
in _TtGC7SwiftUI19UIHostingControllerV15SwiftUIKeyboard11SwiftUIView_:
	allowedBehaviors (): Value not representable,
	host (): Value not representable,
	customTabItem (): Value not representable,
	toolbarCoordinator (): Value not representable,
	swiftUIToolbar (): Value not representable,
	toolbarBridge (): Value not representable,
	keyboardShortcutBridge (): Value not representable,

Good old _ivarDescription is still useful and shows Swift ivars as well; it can’t show the real type, but it’s good enough to confirm that there’s indeed a keyboardShortcutBridge.

What Sets keyboardShortcutBridge?

Now let’s look at what sets keyboardShortcutBridge. It seems there’s a code path where this object isn’t set, so let’s find out if that’s the case. When we load SwiftUI’s binary in Hopper and search for this name, we find quite a few matches:

Hopper search for keyboardShortcutBridge

Now let’s analyze what we see here:

  • There’s a class named KeyboardShortcutBridge in SwiftUI.
  • It has one method marked @objc: _performShortcutKeyCommand:, therefore Objective-C metadata is emitted (init, cxx_destruct).
  • It uses UIKeyCommand under the hood, which is an API you’ll be familiar with if you’ve ever added keyboard support on iOS.
  • There’s a setter for the Swift property that sets this object: SwiftUI.UIHostingController.keyboardShortcutBridge.setter.

Using Xcode’s breakpoint list isn’t working too well for SwiftUI. Adding the setter there isn’t working (fully qualified). Instead, let’s try using LLDB directly and fuzzy-searching for the breakpoint. You’ll want to stop your program early (before UIHostingController is created) and add the breakpoint manually:

(lldb) breakpoint set --func-regex keyboardShortcutBridge
Breakpoint 2: 3 locations.

Great! Now let’s look at the three matches:

(lldb) breakpoint list
Current breakpoints:
1: file = '/Users/steipete/Projects/TempProjects/SwiftUIKeyboard/SwiftUIKeyboard/ViewController.swift', line = 22, exact_match = 0, locations = 1, resolved = 1, hit count = 1

  1.1: where = SwiftUIKeyboard`SwiftUIKeyboard.ViewController.viewDidAppear(Swift.Bool) -> () + 164 at ViewController.swift:22:20, address = 0x000000010115b444, resolved, hit count = 1

2: regex = 'keyboardShortcutBridge', locations = 3, resolved = 3, hit count = 0
  2.1: where = SwiftUI`generic specialization <SwiftUI.ModifiedContent<SwiftUI.AnyView, SwiftUI.RootModifier>> of SwiftUI.UIHostingController.keyboardShortcutBridge.setter : Swift.Optional<SwiftUI.KeyboardShortcutBridge>, address = 0x00007fff57a376b0, resolved, hit count = 0
  2.2: where = SwiftUI`SwiftUI.UIHostingController.keyboardShortcutBridge.getter : Swift.Optional<SwiftUI.KeyboardShortcutBridge>, address = 0x00007fff57a59960, resolved, hit count = 0
  2.3: where = SwiftUI`SwiftUI.UIHostingController.keyboardShortcutBridge.setter : Swift.Optional<SwiftUI.KeyboardShortcutBridge>, address = 0x00007fff57a59990, resolved, hit count = 0

That’s good enough. And sure enough — in the non-working case, the setter is never hit. Once we apply the workaround, the method is hit:

Xcode backtrace for keyboardShortcutBridge

We see that the code responsible for calling the setter is in didChangeAllowedBehaviors.

Next, let’s see if there are any other places that would call this setter. I like to use a full pseudo-code export of SwiftUI. You can create this via Hopper > File > Produce Pseudo-Code File For All Procedures…. This will take many hours and produce a file named SwiftUI.m that’s more than 100 MB in size. Once this is done, use a text editor that can open large files,2 and search for SwiftUI.UIHostingController.keyboardShortcutBridge.setter. The only two code paths are these:

  • int _$s7SwiftUI19UIHostingControllerC25didChangeAllowedBehaviors4from2toyAC0gH0Vyx_G_AItF(int arg0)
  • void _$s7SwiftUI19UIHostingControllerC25didChangeAllowedBehaviors4from2toyAC0gH0Vyx_G_AItFAA15ModifiedContentVyAA7AnyViewVAA12RootModifierVG_Tg5(int arg0)

This is mangled Swift, but it’s not hard to see what the unmangled function name is called — it’s our didChangeAllowedBehaviors(from:to") with a lambda inside it, and not anywhere else.

What Triggers didChangeAllowedBehaviors?

What triggers an allowed behavior change? We can search for SwiftUI.UIHostingController.allowedBehaviors.setter, since didChangeAllowedBehaviors is triggered when the setter is invoked:

  • _$s7SwiftUI16AppSceneDelegateC9sceneItemAA0D4ListV0G0VyF()
  • _$s7SwiftUI16RootViewDelegateC07hostingD0_9didMoveToyAA010_UIHostingD0CyxG_So8UIWindowCSgtAA0D0RzlF(int arg0, int arg1)

So there are two mechanisms that trigger this:

  • The SwiftUI-based app lifecycle
  • A root view delegate

This lines up with our previous tests. SwiftUI app lifecycle works, and if we add UIHostingController as a root view controller, the RootViewDelegate also triggers the change. We can check via a fuzzy breakpoint if a RootViewDelegate is created in the non-working variant via breakpoint set --func-regex RootViewDelegate, and sure enough, there are 13 matches, but not one fires.

When searching for RootViewDelegate( in the full-text SwiftUI.m file, there’s only one match, in s7SwiftUI14_UIHostingViewC15didMoveToWindowyyF. This further confirms our theory. It seems Apple simply forgot a code path to create the keyboard shortcut bridge for the most likely use case of using SwiftUI in existing UIKit apps, which is where it makes most sense.

Tweaking the Workaround

We can make the workaround slightly better and pack it into an extension. If we avoid making the temporary window key, we can skip a whole class of issues that appear when the key window is unexpectedly changed:

extension UIHostingController {

    /// Applies workaround so `keyboardShortcut` can be used via SwiftUI.
    ///
    /// When `UIHostingController` is used as a non-root controller with the UIKit app lifecycle,
    /// keyboard shortcuts created in SwiftUI don't work (as of iOS 14.4).
    /// This workaround is harmless and triggers an internal state change that enables keyboard shortcut bridging.
    /// See https://steipete.com/posts/fixing-keyboardshortcut-in-swiftui/
    func applyKeyboardShortcutFix() {
        #if !targetEnvironment(macCatalyst)
        let window = UIWindow()
        window.rootViewController = self
        window.isHidden = false;
        #endif
    }
}

Because the window itself is shown and deallocated within the same run loop, it’ll never be visible. This workaround is safe and only uses public APIs. I reported this issue to Apple via FB8984997. You can read the full bug report and sample project here.

Bonus: Build keyboardShortcut for iOS 13

After fixing the iOS 14 version of keyboard shortcut, I realized that the principle is quite simple, and it can be rewritten in around 100 lines of Swift so that this feature is available on iOS 13 as well. The syntax is practically the same:

Button(action: {
      print("Button Tapped!!")
  }) {
      Text("Button")
  }
.keyCommand("e", modifiers: [.control])

You can read the full gist here.

Conclusion

I hope this post helps folks when they google “keyboardShortcut SwiftUI not working,” provides a safe workaround, and inspires a few people to dig deeper. Swift is harder to reverse engineer than Objective-C is, but it’s still possible. This was the first time I had to set breakpoints for binary Swift symbols, so it’s good to see that this still works when using LLDB manually.

  1. I’ve seen issues with keyboard handling in Catalyst, so I recommend testing everything before you rely on this functionality there. ↩

  2. In the early years, Sublime Text was my editor of choice, but nowadays, the Electron-based Visual Studio Code is way faster in both opening and searching this file and those of a similar size. ↩