在MacOS 14上,打开设置的方式已经改变.到目前为止,我一直使用的代码是:

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

在MacOS 14上,此代码抛出错误消息Please use SettingsLink for opening the Settings scene.

实际问题:如何在MacOS 14(Sonoma)中以编程方式从AppKit打开应用程序设置

推荐答案

这是一种新方法:

@main
struct MyApp: App {

var body: some Scene {
    WindowGroup {
        RootScreen()
    }

    Settings {
        SettingsScreen()
    }

    MenuBarExtra("My App", systemImage: "mic.fill") {
        SettingsLink {
           Text("Settings")
        }
    }
    .keyboardShortcut(".", modifiers: .command)
}

Alternative if you have NSMenu

https://github.com/orchetect/SettingsAccess

import SettingsAccess

private func setupStatusBar() {
    let menu = NSMenu()
    menu.addItem(NSMenuItem(title: "Settings", action: #selector(openSettings), keyEquivalent: ""))

    statusBarItem = NSStatusBar.system.statusItem(withLength: CGFloat(NSStatusItem.variableLength))
    statusBarItem!.menu = menu
    statusBarItem!.button?.image = NSImage(systemSymbolName: "mic.fill", accessibilityDescription: nil)
}

@objc private func openSettings() {
    if #available(macOS 14, *) {
        appState?.openSettingsSignal.send()
    }
}

---

import SettingsAccess

@main
struct MyApp: App {

    var body: some Scene {
        WindowGroup {
            RootScreen()
                .openSettingsAccess()
        }
    }
}

---

struct RootScreen: View {

    private let appState: AppState
    @Environment(\.openSettings) var openSettings

    var body: some View {
    }
    .onReceive(appState.openSettingsSignal) {
        try? openSettings()
    }
}

---

struct AppState {
    let openSettingsSignal = PassthroughSubject<Void, Never>()
}

Swift相关问答推荐

多个提取来计算核心数据中的记录

如何让CTFontCreateUIFontForLanguage与汉字和表情包协同工作?

更改正在进行的异步任务的完成(SWIFT并发)(&q;)?

OBJC代码中Swift 演员的伊瓦尔:原子还是非原子?

如何在AudioKit中实现自定义音效 node ?

将NavigationSplitView更改为NavigationStack

';NSInternal不一致异常';,原因:';可见导航栏Xcode 15.0 Crash请求布局

UIBezierPath() 和 DragGesture:连接点创建角而不是曲线

在Equatable上引用运算符函数==要求Dictionary.Values符合Equatable

如何让默认函数参数引用另一个函数参数?

为什么在Swift中每次调用Decimal类型的formatted()方法都会越来越慢?

Swift在十进制格式中失go 精度

Xcode 7.3 Swift 的语法高亮和代码完成问题

Swift 协议只能设置?

MKAnnotation Swift

快速在 LLDB 中使用 po

在 Swift 中从服务器播放视频文件

无法将 NSAttributedString.DocumentAttributeKey 类型的值转换为 .DocumentReadingOptionKey

如何快速从另一个视图控制器重新加载表格视图

如何在swift中的每N个字符处为字符串添加分隔符?