SwiftUI - Form Picker - How to prevent navigating back on selected?
Asked Answered
R

1

5

I'm implementing Form and Picker with SwiftUI. There is a problem that it automatically navigates back to Form screen when I select a Picker option, how to keep it stay in selection screen?

Code:

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($0)
                        }
                    }
                }
            }
            .navigationTitle("Select your cheese")
        }
    }
}

Actual:

enter image description here

Expect: (sample from Iphone Settings)

enter image description here

Reserve answered 13/8, 2021 at 11:42 Comment(0)
K
6

You may have to make a custom view that mimics what the picker looks like:

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())
                    }
                }
            }
        }
    }
}
Klinges answered 13/8, 2021 at 19:19 Comment(1)
Thank you! I think this is the only way to do.Reserve

© 2022 - 2024 — McMap. All rights reserved.