简体   繁体   中英

How to use toggle inside picker in swiftui and also change picker value based on toggle

I need to use picker and toggle and based on toggle value picker value needs to be changed.

I have tried to implement it but it shows toggle inside picker but I can't change picker value based on the toggle.

Here's what I have tried so far:

    Picker(selection: $bluetooth.type, label: BluetoothContainer()){
            Toggle(isOn: self.$bluetooth.isBluetoothOn) {
            Text("Bluetooth")
        }

     }

Here's something that updates the picker value based on toggle state.

struct ContentView : View {

    @State var selection: String = ""
    @State var isOn = false

    var body: some View {
        VStack {
            NavigationView {
                Form {
                    Section {
                        Toggle(isOn: $isOn) {
                            Text("Bluetooth")
                        }
                        Picker(selection: $selection, label:
                            Text("Picker Name")
                            , content: {
                                Text( isOn ? "Bluetooth is On" : "Bluetooth is Off").tag(0)
                                Text("Value 2").tag(1)
                        })

                    }
                }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM