SwiftUI 在 iOS 18 / macOS 15 開始提供了一個隱藏的「CAHostingLayer」API,允許開發者直接在 CALayer 中嵌入 SwiftUI 檢視,目前已被 UIKit、AppKit 和 WebKit 內部使用。
隱藏 API 的現狀
- CAHostingLayer 是一個 CALayer 子類別,能夠在層級層面直接承載 SwiftUI 內容
- 目前以 SPI(@_spi(ForUIKitOnly) / @_spi(ForAppKitOnly))標記,不在公開 SwiftUI 標頭中提供
- 自 iOS 18.0 / macOS 15.0 起可用,但需透過特殊手段才能存取
繞過官方限制的實現方式
Apple 的 WebKit 專案採用了巧妙的技術:使用 .swiftinterface 檔案搭配 -module-abi-name SwiftUI 參數,將 SPI 符號重新匯出到獨立模組名稱下,運行時再連結到真實 SwiftUI 框架。開發者可以:
- 將
SwiftUI_SPI.swiftinterface檔案放入專案(如 Modules/Platform/cocoa/) - 在建置設定中新增目錄:
SWIFT_INCLUDE_PATHS = $(inherited) $(SRCROOT)/Modules/Platform/cocoa/ - 使用
import SwiftUI_SPI即可存取
實際使用範例
建立承載層的方式簡單直接:初始化 CAHostingLayer 時傳入 SwiftUI 檢視作為 rootView,設定層的邊界尺寸,即可將其整合到現有的 CALayer 結構中。
開源替代方案
「OpenSwiftUI」專案也提供了此 API,使用者可透過 _spi import OpenSwiftUI 直接使用 CAHostingLayer,無需額外的 swiftinterface 繁瑣步驟。
SwiftUI has a hidden CAHostingLayer API — host your SwiftUI views directly in a CALayer.
— Kyle Ye (@KyleSwifter) March 21, 2026
Currently used internally by UIKit/AppKit and WebKit. Available since iOS 18 / macOS 15.
I wrote a guide on how to access it without Apple's internal SDK 👇https://t.co/M5gAbvtIlQ pic.twitter.com/JVsNW8Uxpa
Also worth noting — OpenSwiftUI provides this API too. If you're using OpenSwiftUI, you can use CAHostingLayer directly via _spi import OpenSwiftUI without the extra swiftinterface workaround.
— Kyle Ye (@KyleSwifter) March 21, 2026
See #831 and #832 for more detail. pic.twitter.com/kXI8Wt4VgN
