NSApplication 是 macOS 应用程序的核心对象,代表整个正在运行的 App 实例。
它属于 AppKit 框架,用于管理 macOS App 的生命周期、事件分发、窗口管理、菜单控制等核心功能。
例如,在commands菜单中,添加NSApp.orderFrontStandardAboutPanel()方法:
CommandMenu("关于") {
Button("关于 ImageSlim") {
NSApp.orderFrontStandardAboutPanel()
}
}
在点击按钮后,调用NSApplication的orderFrontStandardAboutPanel方法,并弹出应用程序的相关信息。

常见方法
1、获取当前 App 实例
let NSApp = NSApplication.shared
SwiftUI 中常见的 NSApp 就是 NSApplication.shared 的简写。
2、显示系统面板(About、Preferences)
NSApp.orderFrontStandardAboutPanel()
NSApp.orderFrontStandardAboutPanel(options: [
.applicationVersion: "1.0.0",
.credits: NSAttributedString(string: "开发者:方君宇")
])
3、控制窗口显示与关闭
NSApp.mainWindow?.close()
NSApp.windows.forEach { $0.orderOut(nil) } // 隐藏所有窗口
4、控制 App 行为(退出、隐藏)
NSApp.terminate(nil) // 退出应用
NSApp.hide(nil) // 隐藏应用(Cmd + H)
NSApp.unhide(nil) // 恢复显示
5、获取窗口列表、激活 App
NSApp.windows // 当前所有窗口数组
NSApp.activate(ignoringOtherApps: true) // 让 App 成为当前激活应用
6、控制主循环(不常用)
NSApp.run() // 启动应用主循环
NSApp.stop(nil) // 停止运行循环
常见示例
在菜单中添加“关于”按钮
CommandMenu("帮助") {
Button("关于 ImageSlim") {
NSApp.orderFrontStandardAboutPanel()
}
}
退出应用
CommandMenu("文件") {
Button("退出") {
NSApp.terminate(nil)
}
.keyboardShortcut("q", modifiers: [.command])
}
还可以自定义“关于”窗口内容。
NSApp.orderFrontStandardAboutPanel(options: [
NSApplication.AboutPanelOptionKey.credits: NSAttributedString(string: "开发者:方君宇"),
NSApplication.AboutPanelOptionKey.applicationVersion: "1.0.0",
])

相关文章
SwiftUI macOS的commands菜单栏修饰符:https://fangjunyu.com/2025/06/19/swiftui-macos%e7%9a%84commands%e8%8f%9c%e5%8d%95%e6%a0%8f%e4%bf%ae%e9%a5%b0%e7%ac%a6/