swiftswiftui

Picker still interactable when disabled


I want to disable a picker view in a form using a bool variable. When disabled, the picker greys out but I can still click on it. I have a simple example here based on the toggle. Any help would be appreciated thanks!

import SwiftUI

struct testView: View {
    @State private var selectedOption: String = "A"
    @State private var pickerEnabled: Bool = true
    var body: some View {
        Form {
            Section("Choose an option") {
                Toggle("Enable Picker", isOn: $pickerEnabled)
                Picker("Options", selection: $selectedOption) {
                    Text("Option A").tag("A")
                    Text("Option B").tag("B")
                    Text("Option C").tag("C")
                }
                .disabled(!pickerEnabled) // tried using either or both these two lines
                .allowsHitTesting(pickerEnabled)
            }
        }
    }
}

#Preview {
    testView()
}

Solution

  • try adding

     .pickerStyle(.menu)
    

    and remove the

     .allowsHitTesting(pickerEnabled)