SwiftUI Form使用Picker时如何阻止选中选项后自动返回上一页
问题原因
SwiftUI 中处于 Form 内的 Picker 默认使用 .automatic 样式,在 iOS 平台该样式会自动封装导航跳转逻辑,选中选项后默认执行 pop 返回上一级操作,因此会出现选完就自动回到 Form 页的情况。
解决方案
目前原生 Picker 没有提供关闭自动返回的参数,最稳妥的方案是手动构建导航跳转逻辑,完全自定义选择页的交互,代码实现如下:
import SwiftUI struct ContentView: View { @State private var selectedStrength = "Mild" let strengths = ["Mild", "Medium", "Mature"] var body: some View { NavigationStack { Form { Section { // 手动实现跳转入口,替代默认Picker的自动跳转 NavigationLink { // 自定义选择页 OptionSelectView(selected: $selectedStrength, options: strengths, title: "Strength") } label: { HStack { Text("Strength") Spacer() Text(selectedStrength) .foregroundColor(.secondary) } } } } .navigationTitle("Select your cheese") } } } // 通用选项选择页,可复用在其他同类选择场景 struct OptionSelectView<T: Hashable & CustomStringConvertible>: View { @Binding var selected: T let options: [T] let title: String var body: some View { List(options, id: \.self) { option in Button { selected = option } label: { HStack { Text(option.description) Spacer() if selected == option { Image(systemName: "checkmark") .foregroundColor(.accentColor) } } } .foregroundColor(.primary) } .navigationTitle(title) .navigationBarTitleDisplayMode(.inline) } }
该实现完全复刻系统设置的交互效果:点击 Form 中的选项行跳转到选择页,选中任意选项仅更新选中状态、显示对勾标记,不会自动触发返回操作,需要用户手动点击左上角返回按钮回到 Form 页。
如果需要兼容 iOS 15 及更早版本,将代码中的 NavigationStack 替换为 NavigationView 即可正常运行。
内容的提问来源于stack exchange,提问作者Thanh Nguyen
相关产品推荐
相关产品推荐

