AppKit 是 macOS 的图形用户界面(GUI)框架,是 Cocoa 的一部分,专门用于构建 macOS 应用的 UI。
它是 macOS 上负责窗口、视图、按钮、菜单栏、事件处理等所有“看得见的界面”的核心框架。
AppKit子类
1、NSApplication:表示 App 本身。
2、NSWindow:窗口。
3、NSView:所有视图组件的基类。
4、NSButton:按钮。
5、NSMenu / NSMenuItem:菜单栏。
6、NSStatusItem:系统右上角状态栏图标。
7、NSResponder:所有事件响应类的父类。
8、NSImage, NSColor, NSEvent:图像、颜色、事件对象等
AppKit示例
import AppKit
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
func applicationDidFinishLaunching(_ notification: Notification) {
let contentRect = NSRect(x: 100, y: 100, width: 400, height: 300)
window = NSWindow(contentRect: contentRect,
styleMask: [.titled, .closable, .resizable],
backing: .buffered,
defer: false)
window.title = "Hello AppKit"
window.makeKeyAndOrderFront(nil)
let button = NSButton(title: "点击我", target: nil, action: nil)
button.frame = NSRect(x: 150, y: 130, width: 100, height: 40)
window.contentView?.addSubview(button)
}
}
AppKit 与 SwiftUI 的区别
1、编程方式: AppKit 是基于类、继承、手动事件响应(OOP),SwiftUI是声明式、基于数据状态(Reactive)。
2、主语言: AppKit)使用Objective-C / Swift编写代码,SwiftUI使用Swift。
3、UI 更新:AppKit手动调用更新,如 setNeedsDisplay,SwiftUI自动响应 @State / @Binding 变化。
4、控件:AppKit 使用NSButton, NSWindow, NSMenu, NSTextView…SwiftUI使用Button, Text, List, NavigationView…
5、可用平台:AppKit仅用于macOS,SwiftUI则可用在iOS、macOS、watchOS、tvOS。
SwiftUI 在底层仍然依赖 Cocoa / UIKit 的渲染与运行时。
SwiftUI是否可以替代AppKit?
不可以,因为SwiftUI 在 macOS 上许多底层依然靠 AppKit 实现。
某些高级功能(如 NSStatusItem、拖拽、多窗口、多菜单栏)目前只能通过 AppKit 完成。
老项目、大公司产品(如 Xcode、Finder)大多是基于 AppKit。
SwiftUI 在 macOS 上还不够成熟,很多场景要嵌套 NSViewRepresentable。
总结
AppKit是Cocoa中用于构建 macOS 图像用户界面的框架,被用于负责窗口、菜单栏、按钮、视图、事件处理。
SwfitUI底层运行时,仍靠AppKit驱动,目前(2025年)并没有过时,但SwiftUI正逐步取代它。
在开发macOS的过程中,常需要使用AppKit + SwiftUI混合开发(比如用SwiftUI写主界面,AppKit写状态栏或菜单栏)。
相关文章
1、macOS核心框架Cocoa:https://fangjunyu.com/2025/06/24/macos%e6%a0%b8%e5%bf%83%e6%a1%86%e6%9e%b6cocoa/
2、macOS核心对象NSApplication:https://fangjunyu.com/2025/06/19/macos%e6%a0%b8%e5%bf%83%e5%af%b9%e8%b1%a1nsapplication/
3、macOS顶部和上下文菜单NSMenu:https://fangjunyu.com/2025/06/23/macos%e9%a1%b6%e9%83%a8%e5%92%8c%e4%b8%8a%e4%b8%8b%e6%96%87%e8%8f%9c%e5%8d%95nsmenu/
4、macOS应用管理类NSWorkspace:https://fangjunyu.com/2025/06/22/macos%e5%ba%94%e7%94%a8%e7%ae%a1%e7%90%86%e7%b1%bbnsworkspace/
5、macOS状态栏图标(系统右上角)NSStatusBar:https://fangjunyu.com/2025/06/24/macos%e7%8a%b6%e6%80%81%e6%a0%8f%e5%9b%be%e6%a0%87%ef%bc%88%e7%b3%bb%e7%bb%9f%e5%8f%b3%e4%b8%8a%e8%a7%92%ef%bc%89nsstatusbar/
6、MacOS图像显示类NSImage:https://fangjunyu.com/2024/11/22/macos%e5%9b%be%e5%83%8f%e6%98%be%e7%a4%ba%e7%b1%bbnsimage/