Unofficial; not affiliated with Apple.
English | 简体中文
CrossSwift (crossswift, SwiftPM manifest CrossSwiftUI) separates the
platform-independent declarative UI engine from platform backends, AppKit and
Apple-framework compatibility shims, and the .xcodeproj build toolchain.
SwiftUIRuntime+SwiftUIRuntimeMacros: platform-independent view values, result builders, scopedEnvironmentValues,@State/@AppStorage/@SceneStorage/@Binding/@FocusState/@FocusedValue/@FocusedObject,@Observable(@Bindable) andObservableObject, compiler macros (@Entryand#Previewover Swift's JSON plugin wire protocol withoutswift-syntax), element tree, layout engine (withSpacer.minLength,.layoutPriority, layout-preserving.hidden(), and viewport virtualization forLazyVStack/LazyHStack/LazyVGrid/LazyHGrid), sibling diff, controls (DisclosureGroup,Gauge,DatePicker,ColorPicker,AsyncImage,Table,ShareLink,.fileImporter/.fileExporter,.redacted,.refreshable,.swipeActions), navigation (NavigationPath+.navigationDestination), presentations, SVG/PDF vector parsing, embeddedSFSymbolCatalog,.xcstringslocalization (XCStringsCatalog), multi-segmentPath.trimmedPath, richCanvas, true linear/radial/angular gradients, timedLongPressGesture+ gesture arbitration, color/transition/layout animations, retained native-control reconciliation (NativeEngine:NativeRendererandNativeTreeSession), and shared pure-Swift backend primitives (BackendSupport:Color.argb,flattenScenes,Elementpaint order & accessibility labels,Path.svgPathData,DrawingMotion,BundleResourceLoader). Imports noNativeAPI, AppKit, browser, or Android APIs.CrossSwiftUI: desktop (NativeAPI) integration for Windows and Linux —WinUIBackend(sole Windows backend overNativeRenderer/CSwiftUIWinUI),GTK4Backend(default Linux backend overNativeRenderer/CSwiftUIGTK4, with opt-outCROSS_SWIFTUI_BACKEND=legacyfallback toLinuxDrawingBackend), centralized backend selection (DesktopBackendSelection),NativeViewBackend, the multi-sceneApp/WindowGroup/Window/Settings/MenuBarExtra(.menuand.window) /Scene.commandsrunner (runApp), native window dark/light chrome synchronization, andCrossAppKit+CrossUIKithosting (NSHostingView,NSHostingController,NSViewRepresentable,NSApplicationDelegateAdaptor,_UIHostingView,UIHostingController,UIHostingConfiguration,UIViewRepresentable,UIViewControllerRepresentable,UIApplicationDelegateAdaptor, plusColor/Font/Image/EdgeInsets↔NSColor/UIColor,NSFont/UIFont,NSImage/UIImage,UIEdgeInsets/NSDirectionalEdgeInsetsconversions andCombineBridgePublished/ObservableObjectPublisherbridging).CSwiftUIWinUI+WinUIHost: C ABI loader and C++/WinRT pure-native WinUI 3 XAML Islands host (CrossSwiftUIWinUI.dll), built viascripts/build-winui3.ps1and dynamically loaded alongside the executable or frombuild/winui3-host/Release.CSwiftUIGTK4+GTK4Host: C ABI loader/IPC bridge and C++ pure-native GTK 4 host (libCrossSwiftUIGTK4.soin-process orCrossSwiftUIGTK4Hostisolated child process whenNativeAPIlinkslibgtk-3), built viascripts/build-gtk4.sh.CrossAppKit+AppKit+CAppKitWindows: cross-platform AppKit views, controls, windows/panels, menus, status items, TextKit 1/2, pasteboard, workspace (/procandxdg-openon Linux, Shell/Win32 on Windows), colors/appearances, fonts, images, shared cross-kit primitives (CrossPrimitives: weak boxes, thread keys, font metrics cache, PNG/image header parsing, file-dialog extension normalization), and Carbon global hotkeys overNativeAPI(with Win32/DWM/Shell/COM/Credential Manager/Accessibility glue inCAppKitWindowson Windows).CrossAppKitcompiles standalone on macOS for unit tests;AppKitis theimport AppKitfacade on Windows and Linux.CrossUIKit+UIKit: cross-platform UIKit application & scene lifecycle (UIApplication,UIApplicationDelegate.main(),UIWindowScene,UIWindow), top-left coordinateUIViewhierarchy with iterative Auto Layout anchor solving andUIStackView,UIControl+UIAction+UIMenu, native-backed controls (UILabel,UIButton,UITextField,UITextView,UIScrollView),UITableView&UICollectionViewwith diffable data sources, view controller containers (UIViewController,UINavigationController,UITabBarController,UIAlertController),UITraitCollection, dynamicUIColor,UIFont&UIFontMetrics,UIImage+UIGraphicsImageRenderer+UIBezierPathsharingCrossAppKit's offscreen drawing pipeline,UIPasteboard,UIScreen, andUIDevice.CrossUIKitcompiles standalone on macOS for unit tests;UIKitis theimport UIKitfacade on Windows and Linux.CrossFoundation+ framework shims: AppleFoundationextensions missing fromswift-corelibs-foundationon Windows/Linux, standalone framework targets (CoreGraphics, fullCombinepublishers/operators/schedulers,CryptoKit,Carbon,UniformTypeIdentifiers,OSLog,os,SQLite3), and 42 system/framework shim modules underSources/AppleShims/(41 Swift framework shims plusCDarwinShims, includingQuartzCore, realSecurityKeychain persistence via Win32 Credential Manager / Linux 0600 XDG keystore, andServiceManagementlogin items on Windows and Linux XDG).SwiftUIWeb: WebAssembly (os(WASI))WindowGrouphosting, DOM/SVG/CSS renderer (including live dark-mode sync,openURL,scrollToDOM sync, CSS filters, conic/radial/linear gradients, and multi-layer SVG/PDF vectors), and web.xcassets/.xcstrings/ SF Symbol loader viaJavaScriptKit.SwiftUIAndroid+CSwiftUIAndroid: Android thread-safeJavaVMasync bridge (AndroidHost),Choreographeranimation loop, dark-mode &openURLsync, and Jetpack Compose host (SwiftUIComposeHost,AndroidStyleRenderers) supporting live switching between Material 3 + Navigation Compose and iOS 27 Liquid Glass styling. See ANDROID.md.SwiftUIHarmony: formal HarmonyOS runtime backend (HarmonyBackend) and parameterized ArkTS host (CrossSwiftUIHost.ets) with async render push, 60 Hz animation ticks, dark-mode sync,rawfile/Resourcesextraction, and HarmonyOS Native / iOS Liquid Glass dual-style rendering.SwiftUI: user-facingimport SwiftUIfacade on non-Apple targets, re-exportingFoundationandSwiftUIRuntimetogether withCrossSwiftUI(+CrossAppKit,CrossUIKit,CrossFoundation,CoreGraphics) on Windows/Linux,SwiftUIWebon WASI,SwiftUIAndroidon Android, orSwiftUIHarmonyunderCROSS_SWIFTUI_HARMONYfor HarmonyOS.CrossXcodeBuild+CrossXcodeBuildCLI: pure-Swift.xcodeproj/.xcworkspaceparser (ScalarTextScanner,OpenStepPlistParser,XCProjParser), canonical CrossSwift module & shim catalog (CrossSwiftCatalog), Apple-framework & SwiftPM dependency adapter,.xcassets/.xcstrings/.icon/.icocompilers, Windows-safeDirectoryWalker&ToolchainDiscovery, and thexcodebuildCLI driver for Windows, Linux, WebAssembly, HarmonyOS (HarmonyBuilder), and Android (AndroidBuilder).
On macOS, swift build / swift test builds SwiftUIRuntime, CrossAppKit,
CrossUIKit, CrossXcodeBuild (xcodebuild), their test suites, and Counter
compiled against Apple's native SwiftUI (enforced with -warnings-as-errors in
CI). Windows, Linux, WebAssembly, HarmonyOS, and Android builds consume
CrossSwift's SwiftUI (and AppKit/UIKit on desktop) facades.
- Begin state collection. Install stored wrappers by structural path, concrete view type, and property position before evaluating each body.
- Track
@Stateand@Observablereads while evaluating bodies and modifiers under scopedEnvironmentValues. A local write invalidates its readers and ancestors; unaffected branches retain their element trees, state, and lifecycle entries.ObservableObjectand untracked geometry-state writes invalidate conservatively. - Normalize fragments (preserving explicit IDs and tags), retain both slots of view layers, and resolve inherited foreground, color scheme, disabled, visibility, and alpha values.
- Compute layout, evaluate geometry children, hoist presentations, prune state, and assign sibling diff keys. The drawing backends supply native text measurers; deterministic metrics serve headless engine tests.
- Diff against the mounted tree, retaining
NodeIDs for matched elements. Keys are local to sibling lists; an unchanged sibling order uses a linear path without key dictionaries or move-list scans. - Publish the updated tree and callbacks, send backend commands, then call
didRender(root). Rendering guards coalesce writes made during a pass; the Windows bridge batches deferred native notifications from a message turn.
Commands are create, insert, remove, move, setProps, and setFrame.
Removing a node disposes its subtree. Actions are looked up by retained
NodeID, so a native callback never invokes a stale body closure. Reentrant
writes are coalesced into at most eight follow-up render passes.
WinUIBackend (in CrossSwiftUI, backed by CSwiftUIWinUI and Sources/WinUIHost)
is the sole SwiftUI rendering backend on Windows. It hosts a WinUI 3
DesktopWindowXamlSource (XAML Island) inside NativeAPI's window/view HWND and
drives a retained tree of pure-native WinUI 3 controls (TextBlock, Button,
TextBox, PasswordBox, ToggleSwitch, Slider, ComboBox, ScrollViewer,
ItemsRepeater, Border, Grid, StackPanel, Canvas, Path, Image,
Flyout/Popup) through NativeRenderer and NativeTreeSession.
- Scrolling, inertia, animations, and rounded clipping run natively on Windows' DirectComposition thread.
LazyVStack,LazyHStack,LazyVGrid, andLazyHGridbind visible rows through WinUI 3ItemsRepeaterwithO(viewport)native control recycling.CrossSwiftUIWinUI.dll(andMicrosoft.WindowsAppRuntime.Bootstrap.dll) are discovered automatically next to the executable, in parentbuild/winui3-host/Release, or viaCROSS_SWIFTUI_WINUI_DLL, andCrossXcodeBuildautomatically builds and stages them.App.mainconfigures Per-Monitor V2 DPI awareness before window creation; embedders callWinUIBackend.prepareApplication()andWinUIBackend.setApplicationIdentifier(_:). OffscreenNSImage/UIImagePNG rasterization for tray icons andUIGraphicsImageRendererlives inCAppKitWindows.
GTK4Backend (in CrossSwiftUI, backed by CSwiftUIGTK4 and Sources/GTK4Host)
is the default SwiftUI backend on Linux. It drives pure-native GTK 4 widgets
(GtkLabel, GtkButton, GtkEntry, GtkTextView, GtkSwitch, GtkScale,
GtkDropDown, GtkScrolledWindow, GtkListView with GtkSignalListItemFactory
O(viewport) recycling, GtkPopover, CSS styling, and GSK/Cairo vector drawing)
through NativeRenderer and NativeTreeSession.
Because NativeAPI currently links libgtk-3 on Linux (for Flutter compatibility)
and GTK 4 forbids loading GTK 3 and GTK 4 in the same process, GTK4Loader.c
automatically detects whether libgtk-3 is resident: it launches the isolated
CrossSwiftUIGTK4Host child process over a low-latency binary socketpair when
GTK 3 is loaded, and loads libCrossSwiftUIGTK4.so in-process otherwise. Set
CROSS_SWIFTUI_BACKEND=legacy to opt out to the legacy GTK 3/Cairo
LinuxDrawingBackend. See DIVERGENCES.md for platform limits.
StateRegistry is process-wide, with state retention and lifecycle ownership
isolated per Renderer root so multiple windows, MenuBarExtra hosts, and
NSHostingView instances maintain independent @State and .onAppear /
.onDisappear / .task lifecycles while sharing @Observable and
ObservableObject models. Bindings are get/set closures; focus bindings wrap
state. Environment values are saved and restored around subtrees. .id and
ForEach identifiers scope both diff identity and stored state. The runtime
interns paths by parent and child key, keeping state lookups independent of view
depth. Reevaluation retains subscriptions to state values the same view still
reads. Published and @Observable writes invalidate observing renderers;
StateObject initialization is lazy. Writes from one action or native
notification batch are published together. ScrollView retains its stored
content when only its internal offset changes. Lifecycle callbacks commit after
mounting, and native run-loop timers service tasks plus property and layout
animations.
Stack measurement sums main-axis sizes and takes the largest cross-axis size.
Padding adds insets; frames constrain and alignment-place a child; layers
measure the base view only. Flexible frames and spacers consume remaining
proposed space. Custom Layout implementations are probed for axis flexibility
rather than assumed to expand horizontally. Measurements are cached by proposal
and sizing inputs. Wrapped text and its measured size share a cache across
measurement and placement. Rebuilt GeometryReader content keeps layout
identities when its sizing inputs match. Placement snapshots copy geometry into
the new tree without replacing callbacks or visual properties. Unchanged
evaluation revisions reuse mounted subtrees when inherited properties also
match: moving them translates their frames, and resizing reflows them. Changed
text, fonts, constraints, alignment, scroll offsets, and child identities
invalidate the relevant caches. Opaque custom layout/guide closures take the
conservative path. Obsolete layout cache entries are reclaimed every eight
passes; changing the text measurer or fallback metrics clears them immediately.
The test suites cover runtime layout, diffing, NativeRenderer / NativeTreeSession,
multi-window state isolation, environment scope, observation, controls/containers,
CrossAppKit & CrossUIKit shims, CrossXcodeBuild project parsing/adaptation,
machine-enforced architectural invariants (ArchitectureGovernanceTests:
catalog/manifest lockstep, import boundaries, bilingual doc parity, Windows-safe
directory/environment rules, and swift-corelibs-xctest @MainActor test
discipline), CrossSwiftUITests (WinUI 3 & GTK 4 pure-native backends),
non-macOS framework shims (CrossShimsTests), and
COMPAT.md symbol verification (COMPATTests). Counter --smoke
opens a real window and exits after three seconds to exercise the native
application loop.