Search code examples
swiftswiftui

SwiftUI Picker triggers onChange twice after selection


Following full code example is firing onChange twice with the same values for old and new state. Similar topic solutions here on Stackoverflow are not solving the issue unfortunately. Help is much appreciated.

import SwiftUI

struct ContentView: View {
    @State var value = "v1"
    var values = ["v1","v2","v3"]
    
    var body: some View {
        if #available(iOS 17.0, *) {
            Picker("", selection: $value) {
                ForEach(values, id: \.self) { entry in
                    Text(entry)
                }.onChange(of: value) { oldValue, newValue in
                    print("currentValue: \(value), oldValue: \(oldValue), newValue: \(newValue)")
                }
            }
        }
    }
}

Solution

  • Moving onChange out of the Picker fixes this.

    Picker("", selection: $value) {
        ForEach(values, id: \.self) { entry in
            Text(entry)
        }
    }
    .onChange(of: value) { oldValue, newValue in
        print("currentValue: \(value), oldValue: \(oldValue), newValue: \(newValue)")
    }