如何在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
相关产品推荐
相关产品推荐

