Every macOS developer has lived the same cycle: blown away by SwiftUI, shipping something that runs in three days of work; two weeks later, stuck on a requirement that “looks easy,” digging through AppKit docs. That’s exactly how I learned it the first time — building a document tool with local search, the list page done in SwiftUI in a day, then three full days lost on “each window remembers its own scroll position,” solved in half an hour once I went back to the AppDelegate and hooked up NSWindow’s delegate.
So this isn’t a framework war. SwiftUI is for “fast,” AppKit is for “correct,” and the question was never which one to pick — it’s when to let each one play. Here’s my practice: why SwiftUI’s honeymoon always ends, my three-layer split, three “stop hesitating, bring AppKit back” signals, where Core ML belongs, and a checklist you can start on tonight.
SwiftUI’s Honeymoon Phase
SwiftUI’s great first impression is well-earned. Declarative UI is genuinely fun: state changes, the interface follows; live previews; a tidy page in a few lines of VStack and HStack. For content display and basic interaction, it’s fast and good — productivity through the roof.
But macOS isn’t iPhone. Desktop-tool users expect the full infrastructure: stable window behavior, a complete menu bar, smooth shortcuts, accurate drag and drop, system-consistent text selection. SwiftUI grew up mobile-first; a lot of what it has on macOS is “borrowed maturity” — usable, until the edges show.
The honeymoon usually ends with three warning signs. First, windows. WindowGroup reads beautifully, but the moment you need “each window remembers its own state” or “confirm before closing,” its behavior starts drifting, and you catch yourself wanting to touch NSWindow directly. Second, focus. Text fields fighting lists for focus, wrong Tab order — SwiftUI’s focus APIs on macOS are often “theoretically available.” Third, list performance. My own measurement: a 5,000-row table with thumbnails drops to around 40fps scrolling in SwiftUI’s List, while NSTableView holds 60 with its mature row reuse.
There’s a very reliable self-test: the moment you start googling “how to make SwiftUI behave like NSTableView,” the answer is already written in the question — just use NSTableView.
My Three-Layer Split
My approach is three layers, each minding its own business:
- SwiftUI: page structure, forms, state-driven display — owns "fast"
- AppKit: windows, menus, input focus, bridging complex controls — owns "correct"
- Shared layer: data models, commands, file system, Core ML inference service — usable by all
The big win: no need to pick a side up front. New projects always start in SwiftUI — speed first, get the skeleton running. AppKit is “hired for specialties” only. The bridging posture is fixed too: wrap an AppKit control in NSViewRepresentable, let the Coordinator act as translator, and have the two sides talk through bindings and callbacks.
Say you want a native search field — just wrap NSSearchField:
struct SearchField: NSViewRepresentable {
@Binding var text: String
var onSubmit: () -> Void
func makeNSView(context: Context) -> NSSearchField {
let field = NSSearchField()
field.delegate = context.coordinator
return field
}
func updateNSView(_ view: NSSearchField, context: Context) {
if view.stringValue != text { view.stringValue = text } // one-way sync, no loops
}
func makeCoordinator() -> Coordinator { Coordinator(self) }
class Coordinator: NSObject, NSSearchFieldDelegate {
var parent: SearchField
init(_ parent: SearchField) { self.parent = parent }
func controlTextDidChange(_ obj: Notification) {
if let f = obj.object as? NSSearchField { parent.text = f.stringValue }
}
func controlTextDidEndEditing(_ obj: Notification) { parent.onSubmit() }
}
}
Window-level takeover goes through the AppDelegate. Hang an @NSApplicationDelegateAdaptor on your SwiftUI App and you get the real NSWindow for fine control — remembering window positions, intercepting close, customizing toolbars, a half-hour job:
class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
func applicationDidFinishLaunching(_ note: Notification) {
NSApp.windows.first?.delegate = self
}
func windowShouldClose(_ sender: NSWindow) -> Bool {
return confirmUnsavedChanges() // confirm unsaved changes first
}
}
Menus and shortcuts are even simpler — no AppKit needed, just add them in SwiftUI’s commands:
.commands {
CommandMenu("Actions") {
Button("Quick Search") { openPalette() }
.keyboardShortcut("k", modifiers: .command)
}
}
The tradeoff here is mental-model switching. SwiftUI is “state changes, UI follows”; AppKit is “I manipulate the views directly.” When mixing, never let the two sides write each other’s state — the Coordinator and delegates exist to do that translation. Get the translation layer right, and mixing is steadier than either side alone.
Three Signals to Bring AppKit Back Decisively
Signal one: multi-window lifecycle. The classic case is a document tool: each window has its own document, its own scroll position, and must restore after reopening. SwiftUI’s WindowGroup plus window restoration is fine for simple cases; complex ones drift. Writing NSWindowDelegate directly gives far more deterministic behavior. Remembering window positions is a three-delegate-method job.
Signal two: complex tables, sidebars, command menus, shortcut systems. A table with column sorting, multi-select, and row dragging is what NSTableView/NSTableColumn spent twenty years polishing; a ⌘K-style command palette built on NSMenu plus NSEvent.addLocalMonitor for global key listening is more reliable than hand-rolled SwiftUI gestures. Half of a desktop productivity tool’s “desktop-ness” comes from this infrastructure.
Signal three: scrolling, focus, drag and drop, list performance. The 40fps-vs-60fps gap on 5,000 rows I mentioned earlier. Drag and drop too: NSDraggingDestination hands you the drag source, modifier keys, and live position — onDrop gives you much thinner information. And text selection needs no argument: native NSTextView’s double-click-to-select-word, triple-click-to-select-paragraph, system dictionary integration — users’ fingers remember all of it. Ship a “close enough” rewrite and they’ll notice on day one.
Where Core ML Lives
Model inference and UI frameworks should run on parallel tracks. My setup is a standalone service layer — an actor for thread safety — and views only subscribe to state:
actor InferenceService {
private var model: MyModel?
private var cache: [String: MLResult] = [:]
func predict(_ input: MLInput) async throws -> MLResult {
let key = input.cacheKey
if let hit = cache[key] { return hit }
if model == nil { model = try MyModel() } // lazy load: into memory on first use
let result = try await model!.prediction(input: input.features)
cache[key] = result
return result
}
}
A few orders of magnitude explain “don’t put it in the view”: a ~200MB image-classification model takes 1–2 seconds to cold-load, sits in hundreds of MB of resident memory, and after warming up runs single-image inference in tens of milliseconds. If model init lives in a view’s body or onAppear, every tab switch can trigger a cold start — that’s where the stutter comes from. With lazy loading plus input-hash caching, the view only handles two states — “inferring” and “got result” — and you can swap SwiftUI for AppKit freely while the service layer doesn’t move an inch.
Start Tonight
A checklist you can begin with this evening:
- Start new projects in SwiftUI — no pre-picked side; speed first, get the skeleton running.
- The first time you feel yourself “working around,” stop: check whether it’s a window, menu, focus, or complex-control problem — if yes, write your first NSViewRepresentable; the search-field example above is copy-ready.
- Pull model calls into an actor service layer: the check is simple — if MLModel init appears in a view, extract it.
- Shortcuts and menus go through commands; try the NSMenu approach for a ⌘K palette first, don’t hand-roll it in SwiftUI.
- Window state goes through NSWindow delegates: remembering positions, intercepting close — a three-delegate-method job.
- When scrolling stutters, measure frame rate before rewriting: run Instruments once, confirm it’s a row-reuse problem, then call in NSTableView. Don’t rewrite on vibes.
One backstop rule: if the same logic has to be written twice — once in SwiftUI, once in AppKit — it’s in the wrong layer. Sink it into the shared layer.
FAQ
Do I have to pick between SwiftUI and AppKit?
No need to pick a side up front. Just layer: SwiftUI does page structure, forms, state display; AppKit handles windows, menus, focus, and bridging complex controls; data models and Core ML inference live in the shared layer. Bridge with NSViewRepresentable, Coordinator as translator.
When should I decisively go back to AppKit?
Three signals: multi-window lifecycle starts drifting; you’re building complex tables, sidebars, command menus, or a shortcut system; you keep working around scrolling, focus, text selection, drag and drop, or list performance. Any one of them — don’t hesitate.
What counts as truly native feel?
Not looking like macOS — the user never once noticing “this is a wrapper” in edge-case interactions. Double-click to select a word, dragging files in, window restoration — users’ fingers remember these.
Where should Core ML inference code go?
A standalone actor service layer, with the caching strategy, lazy-loading the model. Views subscribe to two states — “inferring” and “got result” — and never touch model lifecycle directly.
What do I check first when list scrolling stutters?
Measure frame rate in Instruments first, confirm it’s a row-reuse problem. SwiftUI’s List easily drops to ~40fps on thousands of complex cells; NSTableView holds 60. Measure, then act.
The X-thread version
1/ Everyone who writes macOS tools in SwiftUI lives the same cycle: three days of bliss, then two weeks later stuck on a requirement that “looks easy,” quietly digging through AppKit docs. My first crash: “each window remembers its own scroll position” — three days lost, solved in half an hour once I went back to the AppDelegate and hooked up NSWindow’s delegate.
2/ The conclusion first: SwiftUI is for “fast,” AppKit is for “correct.” The question was never which one — it’s when to let each one play. My split in three sentences: SwiftUI owns page structure and state display, AppKit owns windows, menus, and focus, and data models plus Core ML inference live in a shared layer everyone can use.
3/ Signal one: multi-window lifecycle starts drifting. Document tools need each window to keep its own document and scroll position, and restore after reopening. SwiftUI’s WindowGroup drifts when it gets complex. Remembering window positions is three NSWindow delegate methods — don’t fight declarative abstractions.
4/ Signal two: you’re building complex tables, sidebars, command menus, or a shortcut system. A table with column sorting, multi-select, and dragging is what NSTableView spent twenty years polishing; a ⌘K palette on NSMenu plus NSEvent global listening beats hand-rolled SwiftUI gestures. Half of a desktop tool’s “desktop-ness” comes from this infrastructure.
5/ Signal three: you keep working around scrolling, focus, drag and drop, or list performance. My measurement: 5,000 rows with thumbnails drop SwiftUI’s List to ~40fps; NSTableView holds 60. When it stutters, measure frame rate in Instruments first, confirm row reuse, then call in NSTableView. Don’t rewrite on vibes.
6/ The bridging posture is fixed: wrap an AppKit control in NSViewRepresentable, let the Coordinator translate, and have the two sides talk only through bindings and callbacks. A native search field is just a wrapped NSSearchField, a dozen lines. Never let the two sides write each other’s state.
7/ Window-level takeover goes through the AppDelegate: hang @NSApplicationDelegateAdaptor on your SwiftUI App and you get the real NSWindow. Confirm-unsaved-changes before close, remembering positions, custom toolbars — all half-hour jobs, no full rewrite needed.
8/ Menus and shortcuts don’t even need AppKit — SwiftUI’s commands suffice: add a button in a CommandMenu, one line of .keyboardShortcut(“k”, modifiers: .command), and ⌘K exists. Walk this road first; sink deeper only when it’s not enough.
9/ Where does Core ML go? A standalone actor service layer: lazy model loading plus input-hash caching. Orders of magnitude: a 200MB model cold-loads in 1–2s, sits in hundreds of MB of memory, runs single-image inference in tens of ms after warm-up. Put init in a view body and every tab switch risks a cold start. Views subscribe to two states: “inferring” and “got result.”
10/ One backstop rule: if the same logic must be written twice — once in SwiftUI, once in AppKit — it’s in the wrong layer. Sink it into the shared layer. Start tonight: new projects in SwiftUI → stop and judge the first time you “work around” → extract MLModel init the moment it appears in a view.
11/ The full post has three copy-ready code snippets and two architecture collages: https://citygenius-blog.pages.dev/article/swiftui-appkit — native feel isn’t looking like macOS, it’s the user never once noticing “this is a wrapper” in the edge-case interactions.
每个 macOS 开发者大概都走过同一个循环:被 SwiftUI 惊艳,开三天工就做出一个能跑的东西;两周之后,卡在某个”看起来不难”的需求上,开始翻 AppKit 的文档。我第一次就是这么栽的——做一个带本地搜索的文档工具,列表页用 SwiftUI 一天写完,然后死在”多窗口每个记住自己的滚动位置”上,绕了整整三天,最后回到 AppDelegate 里接上 NSWindow 的代理,半小时搞定。
所以这篇不是框架之争。SwiftUI 负责”快”,AppKit 负责”对”,问题从来不是选哪个,而是什么时候让谁下场。下面是我的实践:先讲 SwiftUI 的蜜月期为什么总会结束,再讲三层分工,然后给三个”别犹豫了,请回 AppKit”的信号,顺带把 Core ML 放哪一层讲清楚,最后是一份今晚就能动手的操作清单。
SwiftUI 的蜜月期
SwiftUI 的第一印象好,是有道理的。声明式写 UI 的爽点很实在:状态一变,界面自己跟着变;Preview 实时看效果;VStack、HStack 几行代码搭出一个规整页面。对内容展示和基础交互,这套东西又快又好,生产力拉满。
但 macOS 不是 iPhone。桌面工具的用户对”基础设施”有全套期待:窗口行为要稳、菜单栏要全、快捷键要顺、拖拽要准、文本选择要跟系统一致。SwiftUI 是移动优先长大的,搬到 macOS 上的很多能力是”借来的成熟”——能用,但遇到边角就露馅。
蜜月期结束通常有三个前兆。第一,窗口。WindowGroup 的抽象很好写,但一旦要”每个窗口记住自己的状态""关闭时拦截确认”,它的行为就开始飘,你会发现自己想直接摸 NSWindow。第二,焦点。文本框和列表抢焦点、Tab 键顺序不对,SwiftUI 的焦点 API 在 macOS 上经常是”理论上有”。第三,列表性能。我自己测过:5000 行带缩略图的表格,SwiftUI 的 List 滚起来能掉到 40fps 左右,NSTableView 靠成熟的行级复用稳在 60。
有个很准的自测方法:当你开始在网上搜”SwiftUI 怎么实现 NSTableView 那样的行为”时,答案其实已经写在问题里了——直接用 NSTableView。
我的三层分工
我的做法是分三层,谁也别抢谁的活:
- SwiftUI:页面骨架、表单、状态驱动展示——负责"快"
- AppKit:窗口、菜单、输入焦点、复杂控件桥接——负责"对"
- 共享层:数据模型、命令、文件系统、Core ML 推理服务——谁都能用
这样做最大的好处是不用开局站队。新工程一律 SwiftUI 起手,速度优先;AppKit 是”专项雇佣”,只接它擅长的活。桥接的姿势也很固定:NSViewRepresentable 包一层 AppKit 控件,Coordinator 当翻译官,两边通过绑定和回调通信。
比如要一个原生搜索框,直接包 NSSearchField:
struct SearchField: NSViewRepresentable {
@Binding var text: String
var onSubmit: () -> Void
func makeNSView(context: Context) -> NSSearchField {
let field = NSSearchField()
field.delegate = context.coordinator
return field
}
func updateNSView(_ view: NSSearchField, context: Context) {
if view.stringValue != text { view.stringValue = text } // 单向同步,避免循环
}
func makeCoordinator() -> Coordinator { Coordinator(self) }
class Coordinator: NSObject, NSSearchFieldDelegate {
var parent: SearchField
init(_ parent: SearchField) { self.parent = parent }
func controlTextDidChange(_ obj: Notification) {
if let f = obj.object as? NSSearchField { parent.text = f.stringValue }
}
func controlTextDidEndEditing(_ obj: Notification) { parent.onSubmit() }
}
}
窗口层面的接管则走 AppDelegate。SwiftUI 的 App 协议里挂一个 @NSApplicationDelegateAdaptor,就能拿到真正的 NSWindow 做精细控制——记住窗口位置、拦截关闭、定制工具栏,半小时的活:
class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
func applicationDidFinishLaunching(_ note: Notification) {
NSApp.windows.first?.delegate = self
}
func windowShouldClose(_ sender: NSWindow) -> Bool {
return confirmUnsavedChanges() // 有未保存修改先弹确认
}
}
菜单和快捷键更简单,不用碰 AppKit,直接在 SwiftUI 的 commands 里加:
.commands {
CommandMenu("操作") {
Button("快速搜索") { openPalette() }
.keyboardShortcut("k", modifiers: .command)
}
}
这套分工的权衡点在于心智切换。SwiftUI 是”状态变,UI 跟着变”;AppKit 是”我直接操作视图”。混用时千万别让两边互相写对方的状态——Coordinator 和 delegate 就是干这个翻译活的,写清楚了,混用反而比纯用一边更稳。
三个信号,果断请回 AppKit
信号一:多窗口生命周期。典型场景是文档类工具:每个窗口有自己的文档、自己的滚动位置,关掉重开要恢复。SwiftUI 的 WindowGroup 加窗口恢复,简单场景没问题,复杂了行为就飘。这时候直接拿 NSWindowDelegate 写,确定性高得多。记住窗口位置这种需求,三行代理方法的事。
信号二:复杂表格、侧边栏、命令菜单、快捷键体系。带列排序、多选、行拖拽的表格,NSTableView/NSTableColumn 是二十年打磨出来的;⌘K 那种命令面板,NSMenu 加 NSEvent.addLocalMonitor 做全局按键监听,比在 SwiftUI 里拼手势可靠。桌面生产力工具的”桌面感”,一半来自这些基础设施。
信号三:滚动、焦点、拖拽、列表性能。前面提过 5000 行表格 40fps 对 60fps 的差距。拖拽也是:文件拖进窗口,NSDraggingDestination 能拿到拖拽源、修饰键、实时位置,onDrop 给的信息就薄得多。文本选择更不用说,原生 NSTextView 的双击选词、三击选段、系统词典联动,用户手指都记住了,你重写一个”差不多”的版本,第一天就会被察觉。
Core ML 放哪一层
模型推理跟 UI 框架应该是两条平行线。我的做法是单独一个服务层,actor 保证线程安全,视图只订阅状态:
actor InferenceService {
private var model: MyModel?
private var cache: [String: MLResult] = [:]
func predict(_ input: MLInput) async throws -> MLResult {
let key = input.cacheKey
if let hit = cache[key] { return hit }
if model == nil { model = try MyModel() } // 懒加载:第一次用才进内存
let result = try await model!.prediction(input: input.features)
cache[key] = result
return result
}
}
几个量级概念决定了”不能塞进视图里”:一个 200MB 量级的图像分类模型,冷启动加载要 1 到 2 秒,常驻内存几百 MB,热身后单张推理是几十毫秒的量级。如果把模型初始化写在视图的 body 或 onAppear 里,用户每次切个标签页都可能触发一次冷启动——卡顿就是这么来的。懒加载加输入哈希缓存之后,视图只管”显示推理中 / 显示结果”两个状态,SwiftUI 还是 AppKit 随便换,服务层纹丝不动。
现在就能动手
今晚就能开始的清单:
- 新工程 SwiftUI 起手,别预设站队,速度优先把骨架跑起来。
- 第一次感到”绕路”就停下来:判断是不是窗口、菜单、焦点、复杂控件的问题——是的话,写你的第一个 NSViewRepresentable,上面搜索框的例子直接抄。
- 把模型调用抽成 actor 服务层:检查点很简单——视图里出现 MLModel 初始化,就抽走。
- 快捷键和菜单走 commands,⌘K 命令面板先用 NSMenu 方案,别在 SwiftUI 里硬拼。
- 窗口状态用 NSWindow 代理管:记住位置、拦截关闭就行。
- 滚动卡了先量帧率再动手:Instruments 跑一遍,确认是行复用问题再请 NSTableView,别凭感觉重写。
还有一条兜底规则:同一份逻辑如果要在 SwiftUI 和 AppKit 里各写一遍,说明它放错了层——下沉到共享层。
常见问题
SwiftUI 和 AppKit 必须二选一吗?
不用开局站队。分层就行:SwiftUI 做页面骨架、表单、状态展示;AppKit 管窗口、菜单、焦点、复杂控件桥接;数据模型和 Core ML 推理放在共享层。桥接用 NSViewRepresentable,Coordinator 当翻译官。
什么时候该果断回到 AppKit?
三个信号:多窗口生命周期开始飘;要做复杂表格、侧边栏、命令菜单、快捷键体系;在滚动、焦点、文本选择、拖拽、列表性能上频繁绕路。出现任意一个,别犹豫。
什么叫真正的原生体验?
不是长得像 macOS,而是用户在边角操作时一次也察觉不到”这是个壳”。双击选词、拖拽文件、窗口恢复——这些细节用户手指都记住了。
Core ML 推理代码应该放哪?
独立的 actor 服务层,和缓存策略一起,懒加载模型。视图只订阅”推理中 / 有结果”两个状态,不直接碰模型生命周期。
列表滚动掉帧先查什么?
先上 Instruments 量帧率,确认是不是行复用问题。SwiftUI 的 List 在几千行复杂 cell 下容易掉到 40fps 左右,NSTableView 能稳住 60。量完再动手。
本篇的 X 速览版
1/ 用 SwiftUI 写 macOS 工具的人,基本都走过同一个循环:前三天爽到飞起,两周后卡在一个”看起来不难”的需求上,开始默默翻 AppKit 文档。我第一次栽在”多窗口各记各的滚动位置”,绕了三天,最后回 AppDelegate 接 NSWindow 代理,半小时搞定。
2/ 先说结论:SwiftUI 负责”快”,AppKit 负责”对”。问题从来不是选哪个,而是什么时候让谁下场。我的分层就三句话:SwiftUI 管页面骨架和状态展示,AppKit 管窗口菜单焦点,数据模型和 Core ML 推理住在谁都能用的共享层。
3/ 信号一:多窗口生命周期开始飘。文档类工具每个窗口有自己的文档和滚动位置,关掉重开要恢复。SwiftUI 的 WindowGroup 复杂了行为就飘。记住窗口位置是三行 NSWindow 代理方法的事,别跟声明式抽象较劲。
4/ 信号二:你要做复杂表格、侧边栏、命令菜单、快捷键体系。带列排序多选拖拽的表格,NSTableView 打磨了二十年;⌘K 命令面板用 NSMenu + NSEvent 全局监听,比 SwiftUI 里拼手势稳得多。桌面工具一半的”桌面感”来自这些基础设施。
5/ 信号三:滚动、焦点、拖拽、列表性能开始频繁绕路。我实测:5000 行带缩略图的表格,SwiftUI List 滚起来掉到 40fps 左右,NSTableView 稳在 60。卡了先上 Instruments 量帧率,确认是行复用问题再请 NSTableView,别凭感觉重写。
6/ 桥接姿势是固定的:NSViewRepresentable 包一层 AppKit 控件,Coordinator 当翻译官,两边只通过绑定和回调通信。比如原生搜索框,直接包 NSSearchField,十来行代码。千万别让两边互相写对方的状态。
7/ 窗口层面的接管走 AppDelegate:在 SwiftUI 的 App 里挂 @NSApplicationDelegateAdaptor,就能拿到真正的 NSWindow。拦截关闭前弹”未保存修改”确认、记住窗口位置、定制工具栏——都是半小时的活,不用重写整个 App。
8/ 菜单和快捷键甚至不用碰 AppKit,SwiftUI 的 commands 就够:CommandMenu 加按钮,一行 .keyboardShortcut(“k”, modifiers: .command),⌘K 就有了。先把这条路走通,不够再下沉。
9/ Core ML 放哪?单独一个 actor 服务层,懒加载模型 + 输入哈希缓存。200MB 的模型冷启动 1–2 秒、常驻几百 MB 内存、热身后单张推理几十毫秒。写在视图 body 里,用户切个标签页就触发一次冷启动。视图只订阅”推理中/有结果”两个状态。
10/ 兜底规则只有一条:如果同一份逻辑要在 SwiftUI 和 AppKit 里各写一遍,说明它放错了层——下沉到共享层。今晚就能动手:新工程 SwiftUI 起手 → 第一次”绕路”就停下来判断 → 视图里出现 MLModel 初始化就抽走。
11/ 完整版在博客,带三段可直接抄的代码和两张架构拼贴图:https://citygenius-blog.pages.dev/article/swiftui-appkit ——原生体验不是长得像 macOS,而是用户在边角操作上一次也察觉不到”这是个壳”。