我创建了一个简单的仅适用于 macOS 的 SwiftUI 应用程序,并按照 Apple 的说明添加了一个设置屏幕:
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
RootView()
}
Settings {
SettingsView()
}
}
}
它有效:首选项选项显示在应用程序菜单中。现在,我还想以编程方式打开此设置窗口,例如单击按钮时。有没有办法实现这个目标?
我希望
NSApplication
中有一种方法,类似于关于窗口,但似乎没有。
在 macOS 13+ 版本上,操作名称 已重命名为 Settings
。 因此,要更新约书亚的答案,这里是使用的解决方案:
NSApp.sendAction(Selector(("showSettingsWindow:")), to: nil, from: nil)
我想知道是否有一个设置场景 ID 可以与新的 openWindow
环境方法一起使用。 :)
if #available(macOS 13, *) {
NSApp.sendAction(Selector(("showSettingsWindow:")), to: nil, from: nil)
} else {
NSApp.sendAction(Selector(("showPreferencesWindow:")), to: nil, from: nil)
}
extension NSApplication {
func openSettings() {
guard let delegate = NSApplication.shared.delegate else { return }
// macOS 13 Ventura
var selector = Selector(("showSettingsWindow:"));
if delegate.responds(to: selector) {
delegate.perform(selector, with: nil, with: nil);
return;
}
// macOS 12 Monterrey
selector = Selector(("showPreferencesWindow:"));
if delegate.responds(to: selector) {
delegate.perform(selector, with: nil, with: nil);
return;
}
}
}
macOS <=12 (Monterey and older), 13 (Ventura) & 14 (Sonoma):
if #available(macOS 14.0, *) {
SettingsLink {
Text("Settings")
}
}
else {
Button(action: {
if #available(macOS 13.0, *) {
NSApp.sendAction(Selector(("showSettingsWindow:")), to: nil, from: nil)
}
else {
NSApp.sendAction(Selector(("showPreferencesWindow:")), to: nil, from: nil)
}
}, label: {
Text("Settings")
})
}