
最新 SwiftUI API 参考基于使用 Sosumi MCP 对 Apple 文档的比较我们找到了推荐使用的最新 API。本文件列出了什么是现代替代品。关于发现软废弃 API 时如何处理——何时迁移、何时保持不动、以及无关编辑的作用域规则——请参阅references/soft-deprecation.md。要在新的 SDK 发布后刷新此列表请运行.agents/skills/update-swiftui-apis/SKILL.md中的维护技能。目录始终使用iOS 15当目标是 iOS 16当目标是 iOS 17当目标是 iOS 18当目标是 iOS 26始终使用iOS 15这些 API 已被废弃足够久没有理由再使用旧变体。紧凑替代品这些替代品的 API 形状变化最小。大多数是近乎直接的替换少数需要额外的参数或结构调整navigationTitle(_:)代替navigationBarTitle(_:)toolbar { ToolbarItem(...) }代替navigationBarItems(...)结构性变化toolbarVisibility(.hidden, for: .navigationBar)代替navigationBarHidden(_:)statusBarHidden(_:)代替statusBar(hidden:)ignoresSafeArea(_:edges:)代替edgesIgnoringSafeArea(_:)preferredColorScheme(_:)代替colorScheme(_:)foregroundStyle(_:)代替foregroundColor(_:)例如.foregroundStyle(.primary)clipShape(.rect(cornerRadius:))代替cornerRadius()textInputAutocapitalization(_:)代替autocapitalization(_:)注意.never取代.noneanimation(_:value:)代替animation(_:)增加必需的value:参数向后部署到 iOS 13列表与表单使用尾随闭包Section初始化器而不是位置参数的 header/footer View 初始化器。单一标题形式仍然是当前用法不应视为已废弃// 当前 - 单一标题 LocalizedStringKey 初始化器Section(Settings){Toggle(Notifications,isOn:.constant(true))}// 替代 - content/header/footer 尾随闭包初始化器Section{Toggle(Notifications,isOn:.constant(true))}header:{Text(Settings)}footer:{Text(Changes apply immediately.)}// 已废弃/重命名 - 位置参数 header/footer View 参数Section(header:Text(Settings),footer:Text(Changes apply immediately.)){Toggle(Notifications,isOn:.constant(true))}Section(header:Text(Settings)){Toggle(Notifications,isOn:.constant(true))}Section(footer:Text(Changes apply immediately.)){Toggle(Notifications,isOn:.constant(true))}呈现始终使用.confirmationDialog(_:isPresented:actions:message:)代替actionSheet(...)。始终使用.alert(_:isPresented:actions:message:)代替alert(isPresented:content:)。两者都接受标题String、isPresented: BindingBool、带Button项支持role: .destructive/.cancel的actions构建器以及可选的message构建器.alert(Delete Item?,isPresented:$showAlert){Button(Delete,role:.destructive){deleteItem()}Button(Cancel,role:.cancel){}}message:{Text(This action cannot be undone.)}文本输入始终使用onSubmit(of:_:)和focused(_:equals:)代替TextField的onEditingChanged/onCommit回调。FocusStateprivatevarisFocused:BoolTextField(Search,text:$query).focused($isFocused).onSubmit{performSearch()}无障碍始终使用专门的无障碍修饰符而不是通用的accessibility(...)变体。使用.accessibilityLabel()、.accessibilityValue()、.accessibilityHint()、.accessibilityAddTraits()、.accessibilityHidden()代替.accessibility(label:)、.accessibility(value:)等。自定义环境/容器值始终使用Entry宏而不是手动实现EnvironmentKey。Entry宏在 Xcode 16 中引入并向后部署到所有 OS 版本。// 现代 — 一行取代约 10 行 EnvironmentKey 样板代码extensionEnvironmentValues{EntryvarmyCustomValue:StringDefault value}样式始终使用Button而不是onTapGesture()除非你需要点击位置或次数。Button(Tap me){performAction()}// 仅当你需要位置或次数时才使用 onTapGestureImage(photo).onTapGesture(count:2){handleDoubleTap()}当目标是 iOS 16导航使用NavigationStack或NavigationSplitView代替NavigationView。基于值的NavigationLink(value:)搭配.navigationDestination(for:)取代基于目的地的链接。NavigationStack{List(items){iteminNavigationLink(value:item){Text(item.name)}}.navigationDestination(for:Item.self){DetailView(item:$0)}}简单重命名tint(_:)代替accentColor(_:)autocorrectionDisabled(_:)代替disableAutocorrection(_:)剪贴板对于用户发起的粘贴 UI优先使用PasteButton以避免粘贴提示。它会自动处理权限。仅当你需要编程式或非Transferable的剪贴板访问时才使用UIPasteboard这会触发粘贴权限提示。PasteButton(payloadType:String.self){stringsinpastedTextstrings.first??}当目标是 iOS 17状态管理新代码优先使用Observable而不是ObservableObject。使用State代替StateObject使用Bindable代替ObservedObject。完整的Observable迁移模式请参阅state-management.md。事件使用onChange(of:initial:_:)或onChange(of:) { }代替onChange(of:perform:)。已废弃的变体只传递新值。现代变体提供旧值和新值两者或无参数闭包。无参数最常见.onChange(of: value) { doSomething() }旧值和新值.onChange(of: value) { old, new in ... }带初始触发.onChange(of: value, initial: true) { ... }已废弃.onChange(of: value) { newValue in ... }—— 单参数闭包感官反馈在 SwiftUI 视图中优先使用sensoryFeedback(_:trigger:)及相关重载而不是UIImpactFeedbackGenerator、UISelectionFeedbackGenerator和UINotificationFeedbackGenerator。以声明方式将触觉反馈附加到拥有状态变化的视图上而不是在按钮动作中以命令式方式触发 UIKit 生成器。StateprivatevarisFavoritefalseButton(Favorite,systemImage:isFavorite?heart.fill:heart){isFavorite.toggle()}.sensoryFeedback(.selection,trigger:isFavorite)当反馈只应在特定状态转换时触发使用条件重载.sensoryFeedback(.selection,trigger:phase){old,newinold.inactive||new.expanded}手势MagnifyGesture代替MagnificationGesture通过value.magnification访问缩放量RotateGesture代替RotationGesture通过value.rotation访问角度布局考虑使用containerRelativeFrame()或visualEffect()作为GeometryReader在尺寸和基于位置的效果方面的替代方案。GeometryReader没有被废弃并且对于许多基于测量的布局仍然是必需的。Image(hero).resizable().containerRelativeFrame(.horizontal){length,axisinlength*0.8}visualEffect { content, geometry in ... }—— 无需GeometryReader包装的基于位置的效果视差、偏移。onGeometryChange(for:of:action:)—— 响应特定视图的几何变化对驱动状态/效果很有用。当布局本身依赖几何信息时GeometryReader仍然更好。注意双闭包形式.onGeometryChange(for:CGFloat.self){proxyinproxy.size.height}action:{newHeightinheightnewHeight}.coordinateSpace(.named(scroll))代替.coordinateSpace(name: scroll)。当目标是 iOS 18标签页使用TabAPI 代替tabItem(_:)。TabView{Tab(Home,systemImage:house){HomeView()}Tab(Search,systemImage:magnifyingglass){SearchView()}Tab(Profile,systemImage:person){ProfileView()}}当使用Tab(role:)时所有标签页都必须使用Tab语法。将Tab(role:)与.tabItem()混用会导致编译错误。预览在预览中为动态属性使用Previewable。// 现代iOS 18#Preview{PreviewableStatevarisOnfalseToggle(Setting,isOn:$isOn)}当目标是 iOS 26关于 Liquid Glass APIglassEffect、GlassEffectContainer、玻璃按钮样式请参阅 liquid-glass.md。滚动边缘效果使用scrollEdgeEffectStyle(_:for:)配置滚动边缘行为。ScrollView{// content}.scrollEdgeEffectStyle(.soft,for:.top)背景扩展使用backgroundExtensionEffect()实现边缘延伸的模糊背景。Liquid Glass 侧边栏后面的视图可能出现被裁剪的情况。这个修饰符会镜像并模糊安全区之外的内容使插画保持可见。Image(hero).backgroundExtensionEffect()来源“Build a SwiftUI app with the new design”WWDC25会话 323标签栏使用tabBarMinimizeBehavior(_:)控制标签栏在滚动时的最小化。TabView{// tabs}.tabBarMinimizeBehavior(.onScrollDown)使用tabViewBottomAccessory在标签栏上方放置持久控件。从环境中读取tabViewBottomAccessoryPlacement以便在辅助项折叠进标签栏区域时调整内容。TabView{// tabs}.tabViewBottomAccessory{NowPlayingBar()}使用Tab(role: .search)创建专用的搜索标签页。该标签页会与其他标签页分离并在选中时变形成搜索字段。TabView{Tab(Home,systemImage:house){HomeView()}Tab(Profile,systemImage:person){ProfileView()}Tab(role:.search){SearchResultsView()}}来源“What’s new in SwiftUI”WWDC25会话 256和 “Build a SwiftUI app with the new design”WWDC25会话 323工具栏使用ToolbarSpacer控制工具栏项的编组。固定间距在视觉上分隔相关组弹性间距将项推开。.toolbar{ToolbarItem(placement:.topBarTrailing){Button(Up,systemImage:chevron.up){}}ToolbarItem(placement:.topBarTrailing){Button(Down,systemImage:chevron.down){}}ToolbarSpacer(.fixed)ToolbarItem(placement:.topBarTrailing){Button(Settings,systemImage:gear){}}}使用sharedBackgroundVisibility(.hidden)从单个工具栏项移除玻璃组背景。ToolbarItem(placement:.topBarTrailing){Image(systemName:person.circle.fill).sharedBackgroundVisibility(.hidden)}在工具栏项内容上使用badge(_:)显示指示器。ToolbarItem(placement:.topBarTrailing){Button(Notifications,systemImage:bell){}.badge(unreadCount)}来源“Build a SwiftUI app with the new design”WWDC25会话 323搜索使用searchToolbarBehavior(.minimizable)选择使用最小化的搜索按钮。系统可能会根据可用空间自动将搜索最小化为工具栏按钮。使用此修饰符显式选择启用。NavigationStack{ContentView().searchable(text:$query).searchToolbarBehavior(.minimizable)}来源“Build a SwiftUI app with the new design”WWDC25会话 323动画使用Animatable宏代替手动animatableData声明。该宏从所有可动画属性自动合成animatableData。使用AnimatableIgnored排除特定属性。AnimatablestructWedge:Shape{varstartAngle:AnglevarendAngle:AngleAnimatableIgnoredvardrawClockwise:Boolfuncpath(inrect:CGRect)-Path{/* ... */}}来源“What’s new in SwiftUI”WWDC25会话 256呈现使用navigationZoomTransition让 sheet 从其来源视图变形出现。工具栏项和按钮可以作为过渡来源。.toolbar{ToolbarItem{Button(Add,systemImage:plus){showSheettrue}.navigationTransitionSource(id:addSheet,namespace:namespace)}}.sheet(isPresented:$showSheet){AddItemView().navigationTransitionDestination(id:addSheet,namespace:namespace)}来源“Build a SwiftUI app with the new design”WWDC25会话 323控件使用controlSize(.extraLarge)制作超大号的突出操作按钮。Button(Get Started){}.buttonStyle(.borderedProminent).controlSize(.extraLarge)对需要与容器边角匹配的按钮使用concentric边角样式。Button(Confirm){}.clipShape(.rect(cornerRadius:12,style:.concentric))Slider 现在支持刻度标记和中性值。Slider(value:$speed,in:0.5...2.0,step:0.25){Text(Speed)}ticks:{SliderTick(value:0.6)SliderTick(value:0.9)}.sliderNeutralValue(1.0)来源“Build a SwiftUI app with the new design”WWDC25会话 323富文本使用带AttributedString绑定的TextEditor进行富文本编辑。支持粗体、斜体、下划线、删除线、自定义字体、前景/背景颜色、段落样式和 Genmoji。Stateprivatevartext:AttributedStringHello, world!varbody:someView{TextEditor(text:$text)}来源“Cook up a rich text experience in SwiftUI with AttributedString”WWDC25会话 280网页内容使用WebView显示网页内容。对于更丰富的交互创建一个可观察的WebPage模型。// 简单的 URL 显示WebView(url:URL(string:https://example.com)!)// 带可观察模型StateprivatevarpageWebPage()WebView(page).onAppear{page.load(URLRequest(url:myURL))}.navigationTitle(page.title??)来源“Meet WebKit for SwiftUI”WWDC25会话 231拖放使用dragContainer进行多项目拖放操作。结合DragConfiguration实现自定义拖放行为结合onDragSessionUpdated观察事件。PhotoGrid(photos:photos).dragContainer(for:Photo.self){selectioninreturnselection.map{$0.transferable}}.onDragSessionUpdated{sessioninifsession.phase.endedWithDelete{deleteSelectedPhotos()}}来源“What’s new in SwiftUI”WWDC25会话 256场景桥接UIKit 和 AppKit 生命周期应用现在可以请求 SwiftUI 场景。这使得命令式生命周期应用可以通过UIApplication.shared.activateSceneSession(for:errorHandler:)使用仅 SwiftUI 的场景类型如MenuBarExtra和ImmersiveSpace。来源“What’s new in SwiftUI”WWDC25会话 256快速查找表已废弃推荐起始版本navigationBarTitle(_:)navigationTitle(_:)iOS 15navigationBarItems(...)toolbar { ToolbarItem(...) }iOS 15navigationBarHidden(_:)toolbarVisibility(.hidden, for: .navigationBar)iOS 15statusBar(hidden:)statusBarHidden(_:)iOS 15edgesIgnoringSafeArea(_:)ignoresSafeArea(_:edges:)iOS 15colorScheme(_:)preferredColorScheme(_:)iOS 15foregroundColor(_:)foregroundStyle(_:)iOS 15cornerRadius(_:)clipShape(.rect(cornerRadius:))iOS 15actionSheet(...)confirmationDialog(...)iOS 15alert(isPresented:content:)alert(_:isPresented:actions:message:)iOS 15autocapitalization(_:)textInputAutocapitalization(_:)iOS 15accessibility(label:)等accessibilityLabel()等iOS 15TextFieldonCommit/onEditingChangedonSubmitfocusediOS 15animation(_:)无 valueanimation(_:value:)向后部署iOS 13Section(header:content:)Section(content:header:)未来废弃Section(footer:content:)Section(content:footer:)未来废弃Section(header:footer:content:)Section(content:header:footer:)未来废弃手动EnvironmentKeyEntry宏向后部署Xcode 16NavigationViewNavigationStack/NavigationSplitViewiOS 16accentColor(_:)tint(_:)iOS 16disableAutocorrection(_:)autocorrectionDisabled(_:)iOS 16UIPasteboard.generalPasteButtoniOS 16onChange(of:perform:)onChange(of:) { }或onChange(of:) { old, new in }iOS 17UIImpactFeedbackGenerator/UISelectionFeedbackGenerator/UINotificationFeedbackGeneratorsensoryFeedback(_:trigger:)iOS 17MagnificationGestureMagnifyGestureiOS 17RotationGestureRotateGestureiOS 17coordinateSpace(name:)coordinateSpace(.named(...))iOS 17ObservableObjectObservableiOS 17tabItem(_:)TabAPIiOS 18手动animatableDataAnimatable宏iOS 26sheet 上的presentationBackground(_:)默认 Liquid Glass sheet 材质iOS 26自定义工具栏背景 hackscrollEdgeEffectStyle(_:for:)iOS 26