SwiftUI - 表单选择器 - 如何防止返回所选内容?
SwiftUI - Form Picker - How to prevent navigating back on selected?
我正在使用 SwiftUI 实现 Form 和 Picker。有一个问题,当我 select 选择器选项时它会自动导航回表单屏幕,如何让它留在 selection 屏幕?
代码:
struct ContentView: View {
@State private var selectedStrength = "Mild"
let strengths = ["Mild", "Medium", "Mature"]
var body: some View {
NavigationView {
Form {
Section {
Picker("Strength", selection: $selectedStrength) {
ForEach(strengths, id: \.self) {
Text([=10=])
}
}
}
}
.navigationTitle("Select your cheese")
}
}
}
实际:
预期:(样本来自 Iphone 设置)
您可能需要制作一个模仿选择器外观的自定义视图:
struct ContentView: View {
let strengths = ["Mild", "Medium", "Mature"]
@State private var selectedStrength = "Mild"
var body: some View {
NavigationView {
Form {
Section {
NavigationLink(destination: CheesePickerView(strengths: strengths, selectedStrength: $selectedStrength)) {
HStack {
Text("Strength")
Spacer()
Text(selectedStrength)
.foregroundColor(.gray)
}
}
}
}
.navigationTitle("Select your cheese")
}
}
}
struct CheesePickerView: View {
let strengths: [String]
@Binding var selectedStrength: String
var body: some View {
Form {
Section {
ForEach(0..<strengths.count){ index in
HStack {
Button(action: {
selectedStrength = strengths[index]
}) {
HStack{
Text(strengths[index])
.foregroundColor(.black)
Spacer()
if selectedStrength == strengths[index] {
Image(systemName: "checkmark")
.foregroundColor(.blue)
}
}
}.buttonStyle(BorderlessButtonStyle())
}
}
}
}
}
}
我正在使用 SwiftUI 实现 Form 和 Picker。有一个问题,当我 select 选择器选项时它会自动导航回表单屏幕,如何让它留在 selection 屏幕?
代码:
struct ContentView: View {
@State private var selectedStrength = "Mild"
let strengths = ["Mild", "Medium", "Mature"]
var body: some View {
NavigationView {
Form {
Section {
Picker("Strength", selection: $selectedStrength) {
ForEach(strengths, id: \.self) {
Text([=10=])
}
}
}
}
.navigationTitle("Select your cheese")
}
}
}
实际:
预期:(样本来自 Iphone 设置)
您可能需要制作一个模仿选择器外观的自定义视图:
struct ContentView: View {
let strengths = ["Mild", "Medium", "Mature"]
@State private var selectedStrength = "Mild"
var body: some View {
NavigationView {
Form {
Section {
NavigationLink(destination: CheesePickerView(strengths: strengths, selectedStrength: $selectedStrength)) {
HStack {
Text("Strength")
Spacer()
Text(selectedStrength)
.foregroundColor(.gray)
}
}
}
}
.navigationTitle("Select your cheese")
}
}
}
struct CheesePickerView: View {
let strengths: [String]
@Binding var selectedStrength: String
var body: some View {
Form {
Section {
ForEach(0..<strengths.count){ index in
HStack {
Button(action: {
selectedStrength = strengths[index]
}) {
HStack{
Text(strengths[index])
.foregroundColor(.black)
Spacer()
if selectedStrength == strengths[index] {
Image(systemName: "checkmark")
.foregroundColor(.blue)
}
}
}.buttonStyle(BorderlessButtonStyle())
}
}
}
}
}
}