swift - SwiftUI Picker triggers onChange twice after selection - Stack Overflow

admin2025-04-18  3

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)")
                }
            }
        }
    }
}

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)")
                }
            }
        }
    }
}
Share asked Jan 30 at 11:27 DuckjdDuckjd 871 silver badge5 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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)")
}
转载请注明原文地址:http://anycun.com/QandA/1744923051a89536.html