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

推荐订阅源

K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - Franky
V
V2EX
Last Week in AI
Last Week in AI
H
Help Net Security
J
Java Code Geeks
WordPress大学
WordPress大学
阮一峰的网络日志
阮一峰的网络日志
Hugging Face - Blog
Hugging Face - Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
A
About on SuperTechFans
月光博客
月光博客
腾讯CDC
小众软件
小众软件
罗磊的独立博客
D
Docker
V
Visual Studio Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
Spread Privacy
Spread Privacy
博客园 - 叶小钗
F
Full Disclosure
Recent Announcements
Recent Announcements
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
L
LangChain Blog
T
The Exploit Database - CXSecurity.com
宝玉的分享
宝玉的分享
美团技术团队
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
L
LINUX DO - 热门话题
博客园 - 三生石上(FineUI控件)
T
Tailwind CSS Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Securelist
Latest news
Latest news
Project Zero
Project Zero
T
Threat Research - Cisco Blogs
NISL@THU
NISL@THU
K
Kaspersky official blog
O
OpenAI News
T
Tenable Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
Cyberwarzone
Cyberwarzone
Vercel News
Vercel News
有赞技术团队
有赞技术团队
P
Proofpoint News Feed
爱范儿
爱范儿
B
Blog RSS Feed
U
Unit 42

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 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 Fixing keyboardShortcut in SwiftUI | 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
Showing Settings from macOS Menu Bar Items: A 5-Hour Journey | Peter Steinberger
Peter Steinberger · 2025-06-17 · via Peter Steinberger

Opening a settings window from a macOS menu bar app should be trivial. It’s not. After spending hours debugging, I’m documenting the gotchas to save you the same frustration.

The Problem

SwiftUI provides SettingsLink for opening settings:

MenuBarExtra("Test", systemImage: "star.fill") {
    SettingsLink {
        Text("Open settings") 
    }
}

Simple, right? Except it doesn’t work reliably in MenuBarExtra. The documentation doesn’t mention this limitation.

According to Apple’s documentation, SettingsLink should “open the app’s settings scene when activated.” However, this assumes your app is already active and has proper window management context - assumptions that don’t hold for menu bar apps.

Why It Fails

Menu bar apps operate differently from regular macOS apps:

  • No dock icon by default - They use NSApplication.ActivationPolicy.accessory
  • Not “active” in the traditional sense - They don’t appear in the app switcher
  • Windows may appear behind other apps - Without proper activation, windows lack focus
  • No SwiftUI graph loaded - Settings needs some SwiftUI view initalized and the menu bar uses AppKit under the hood.

The root issue is that NSApplication treats menu bar apps as background utilities, not foreground applications. This affects how windows are ordered and receive events.

The Evolution of Workarounds

The Old Way

This is how it used to work. Private API, but widely used and simple:

if #available(macOS 13, *) {
    NSApp.sendAction(Selector(("showSettingsWindow:")), to: nil, from: nil)
} else {
    // macOS 12 or earlier
    NSApp.sendAction(Selector(("showPreferencesWindow:")), to: nil, from: nil)
}

This stopped working in Sonoma (14) with the error: “Please use SettingsLink for opening the Settings scene.” Apple deprecated these selectors in favor of SwiftUI’s scene-based approach, but didn’t account for the unique challenges of menu bar apps.

The openSettings Environment Action

Apple provides an openSettings environment action for programmatic access (available since macOS 14.0+):

struct MyView: View {
    @Environment(\.openSettings) private var openSettings

    var body: some View {
        Button("Open Settings") {
            openSettings()
        }
    }
}

This currently works on macOS 15, but doesn’t work on macOS Tahoe (26). The logic needs an existing SwiftUI render tree, and simply calling the environment variable does nothing if none is found.

The workaround? As horrible as it sounds, a hidden window. Of course, that comes with its own issues, unless you massage the window that it’s really off-screen and ideally also doesn’t react to touches.

Hide & Seek

Now, this works, however the window will open in the background, and no amount of makeKeyAndOrderFront(nil) will help. Trust me. I (and Claude) tried plenty variations.

The real reason? macOS doesn’t allow a window to become selected when there’s no Dock icon. And since it’s common to hide the Dock icon for pure Menu Bar apps, that’s a problem.

The workaround? Show the Dock icon just before calling openSettings() and then hiding it again. In a way, this is also convenient for the user as the Icon now represents the “app” - the visible window, and once that closes, we hide the Dock icon again. (via calling NSApp.setActivationPolicy(.accessory)). Of course the whole thing requires some delays to really work, so let me present you the final, working solution (I apologize in advance):

The Working Solution

Here’s the minimal implementation for macOS 14 and higher, using Swift 6:

// Hidden window to provide context
struct HiddenWindowView: View {
    @Environment(\.openSettings) private var openSettings
    
    var body: some View {
        Color.clear
            .frame(width: 1, height: 1)
            .onReceive(NotificationCenter.default.publisher(for: .openSettingsRequest)) { _ in
                Task { @MainActor in
                    // Show dock icon for window focus
                    NSApp.setActivationPolicy(.regular)
                    try? await Task.sleep(for: .milliseconds(100))
                    
                    // Activate and open
                    NSApp.activate(ignoringOtherApps: true)
                    openSettings()
                    
                    // 2. No window ordering - After openSettings(), you might need additional window management to ensure
                    // it comes to front:
                    try? await Task.sleep(for: .milliseconds(200))
                    if let settingsWindow = findSettingsWindow() {
                        settingsWindow.makeKeyAndOrderFront(nil)
                        settingsWindow.orderFrontRegardless()
                    }
                }
            }
            .onReceive(NotificationCenter.default.publisher(for: .settingsWindowClosed)) { _ in
                // Restore menu bar app state when settings closes
                NSApp.setActivationPolicy(.accessory)
            }
    }
}

// Window identifier for settings
static let settingsWindowIdentifier = "com.apple.SwiftUI.Settings"

/// Finds the settings window using multiple detection methods
static func findSettingsWindow() -> NSWindow? {
    // Try multiple methods to find the window
    return NSApp.windows.first { window in
        // Check by identifier
        if window.identifier?.rawValue == settingsWindowIdentifier {
            return true
        }
        
        // Check by title
        if window.isVisible && window.styleMask.contains(.titled) &&
           (window.title.localizedCaseInsensitiveContains("settings") ||
            window.title.localizedCaseInsensitiveContains("preferences")) {
            return true
        }
        
        // Check by content view controller type
        if let contentVC = window.contentViewController,
           String(describing: type(of: contentVC)).contains("Settings") {
            return true
        }
        
        return false
    }
}

// App structure
@main
struct MenuBarApp: App {
    var body: some Scene {
        MenuBarExtra("My App", systemImage: "star.fill") {
            Button("Settings...") {
                NotificationCenter.default.post(name: .openSettingsRequest, object: nil)
            }
            .keyboardShortcut(",", modifiers: .command)
        }
        
        // Required Settings scene
        Settings {
            SettingsView()
                .onDisappear {
                    NotificationCenter.default.post(name: .settingsWindowClosed, object: nil)
                }
        }
        
        // Hidden window for context
        Window("Hidden", id: "HiddenWindow") {
            HiddenWindowView()
        }
        .windowResizability(.contentSize)
        .defaultSize(width: 1, height: 1)
    }
}

extension Notification.Name {
    static let openSettingsRequest = Notification.Name("openSettingsRequest")
    static let settingsWindowClosed = Notification.Name("settingsWindowClosed")
}

The NotificationCenter approach decouples the menu action from the window context, allowing the hidden window to handle the actual settings opening.

For a production-ready implementation with all edge cases (yes, there are some more…) handled, see VibeTunnel’s SettingsOpener.swift.

Scene Order Matters (Unfortunately)

While implementing @steipete’s solution described above, I (@matejkob) discovered another gotcha: the order of scenes in your App’s body actually affects whether this workaround functions correctly.

The working example shown earlier has the scenes in this order:

  1. MenuBarExtra
  2. Settings
  3. Window (hidden)

However, I found that if you arrange them like this (which seems equally logical):

var body: some Scene {
    MenuBarExtra("My App", systemImage: "star.fill") {
        ContentView()
    }
    .menuBarExtraStyle(.menu)
    
    Settings {
        SettingsView()
            .onDisappear {
                NotificationCenter.default.post(name: .settingsWindowClosed, object: nil)
            }
    }
    
    // Hidden window for settings context
    Window("Hidden", id: "HiddenWindow") {
        HiddenWindowView()
    }
    .windowResizability(.contentSize)
    .defaultSize(width: 100, height: 100)
}

The hidden window won’t be “visible” to the SwiftUI environment system (at least not on macOS Sequoia 15.5), and the openSettings() call will fail silently. However, moving the hidden Window scene before the Settings scene makes it work perfectly:

var body: some Scene {
    // Hidden window for settings context - MUST come before Settings
    Window("Hidden", id: "HiddenWindow") {
        HiddenWindowView()
    }
    .windowResizability(.contentSize)
    .defaultSize(width: 100, height: 100)
    
    MenuBarExtra("My App", systemImage: "star.fill") {
        ContentView()
    }
    .menuBarExtraStyle(.menu)
    
    Settings {
        SettingsView()
            .onDisappear {
                NotificationCenter.default.post(name: .settingsWindowClosed, object: nil)
            }
    }
}

This suggests that SwiftUI’s scene resolution and environment propagation happens in declaration order, and the @Environment(\.openSettings) action in the hidden window needs its context established before the Settings scene is processed.

Whether this is an Xcode build system quirk, a SwiftUI implementation detail, or intended behavior is unclear from Apple’s documentation. What is clear is that the hidden window must be declared before the Settings scene for this workaround to function reliably.

This adds yet another layer of undocumented complexity to what should be a simple operation - not only do we need a hidden window and activation policy juggling, but we also need to carefully order our scene declarations to avoid mysterious failures.

Understanding the Workaround

The hidden window serves multiple purposes:

  • Provides a valid window context for the openSettings environment action
  • Allows us to temporarily switch activation policies without visual disruption
  • Gives us a place to handle the complex timing orchestration

The dock icon manipulation (switching between .accessory and .regular) is necessary because macOS only brings windows to the front reliably for apps with dock icons.

Fin

What should be a one-liner in other frameworks requires careful orchestration in SwiftUI. The combination of MenuBarExtra, Settings scenes, and openSettings wasn’t designed with the unique constraints of menu bar apps in mind.

This shouldn’t be so hard. Opening a settings window is one of the most basic operations any app needs to perform. The fact that it requires hidden windows, activation policy juggling, and precise timing delays in 2025 is a testament to how menu bar apps remain second-class citizens in SwiftUI. Until Apple addresses these fundamental issues, we’re stuck with these workarounds.