Ask Your Question
3

How to respond to the reselection of an item in a SwiftUI Picker?

asked 2022-10-13 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-10-27 03:00:00 +0000

lakamha gravatar image

To respond to the reselection of an item in a SwiftUI Picker, you can use the .onChange() modifier.

Here's an example:

struct ContentView: View {
    @State private var selectedColor = "Red"

    var body: some View {
        VStack {
            Text("Selected color: \(selectedColor)")

            Picker("Colors", selection: $selectedColor) {
                Text("Red").tag("Red")
                Text("Green").tag("Green")
                Text("Blue").tag("Blue")
            }
            .pickerStyle(SegmentedPickerStyle())
            .onChange(of: selectedColor) { value in
                print("Selected color changed to \(value)")
            }
        }
    }
}

In this example, we have a Picker with three options, and we're using a segmented picker style.

We're also using the .onChange() modifier to print a message to the console whenever the selected color changes.

You can replace the print() statement with any code you want to execute when the selected item is reselected.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-10-13 11:00:00 +0000

Seen: 14 times

Last updated: Oct 27 '22