You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在macOS 14(Sonoma)中从AppKit编程打开SwiftUI设置

在macOS 14(Sonoma)中通过AppKit编程打开应用设置

问题背景

macOS 14对AppKit打开应用设置的方式做出了变更,原有的兼容代码运行时会抛出错误:
Please use SettingsLink for opening the Settings scene.

此前使用的兼容代码:

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

解决方案

1. 纯AppKit项目适配写法

在macOS 14中,仍可通过AppKit API编程打开设置窗口,只需替换为更规范的选择器调用方式,同时确保应用已配置Settings场景:

if #available(macOS 13, *) {
    NSApp.sendAction(#selector(NSApplication.showSettingsWindow(_:)), to: nil, from: nil)
} else {
    NSApp.sendAction(#selector(NSApplication.showPreferencesWindow(_:)), to: nil, from: nil)
}

也可简化为直接调用方法:

if #available(macOS 13, *) {
    NSApplication.shared.showSettingsWindow(nil)
} else {
    NSApplication.shared.showPreferencesWindow(nil)
}

2. 关键配置要求

必须确保应用的Info.plist中已正确配置Settings场景:

  • 在NSApplicationSceneManifest字典下,添加NSSceneConfigurations数组,包含NSSettingsSceneConfiguration类型的配置
  • 或直接在Xcode项目的「General」标签页中,勾选「Settings」选项自动生成配置

3. 混合SwiftUI场景的情况

如果应用采用SwiftUI的Settings场景,除上述AppKit方式外,也可直接使用SwiftUI提供的SettingsLink组件,该方式更适合在SwiftUI视图中触发设置窗口。

内容的提问来源于stack exchange,提问作者Stephan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 21:32:45