Jos*_*hua 7 macos settings window preferences swiftui
我创建了一个简单的仅限 macOS 的 SwiftUI 应用程序,并按照Apple 的说明添加了一个设置屏幕:
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
RootView()
}
Settings {
SettingsView()
}
}
}
Run Code Online (Sandbox Code Playgroud)
它有效:首选项选项选项显示在应用程序菜单中。现在,我还想以编程方式打开此设置窗口,例如单击按钮时。有没有办法实现这一目标?
我希望 中有一种方法NSApplication,类似于关于窗口,但似乎没有。
小智 30
在 macOS 13+ 版本上,操作名称已重命名为Settings. 因此,要更新约书亚的答案,请使用以下解决方案:
NSApp.sendAction(Selector(("showSettingsWindow:")), to: nil, from: nil)
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一个设置场景 ID 可以与新openWindow环境方法一起使用。:)
小智 10
在 macOS 13+ 上,我使用以下解决方案:
if #available(macOS 13, *) {
NSApp.sendAction(Selector(("showSettingsWindow:")), to: nil, from: nil)
} else {
NSApp.sendAction(Selector(("showPreferencesWindow:")), to: nil, from: nil)
}
Run Code Online (Sandbox Code Playgroud)
通过检查应用程序菜单,我找到了这个解决方案:
NSApp.sendAction(Selector(("showPreferencesWindow:")), to: nil, from: nil)
Run Code Online (Sandbox Code Playgroud)
不过,我认为它可能无法通过使用私有 API 的 App Review,因此仍然欢迎使用不那么阴暗的替代方案。
更新:这实际上已经通过了 App Review,所以我现在将其标记为答案。
以下是macOS <=12(Monterey 及更早版本)、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")
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
565 次 |
| 最近记录: |