SwiftUI Picker onChange or equivalent?

后端 未结 7 1807
南旧
南旧 2020-12-01 09:31

I want to change some other unrelated @State variable when a Picker gets changed but there is no onChanged and it\'s not possible to p

7条回答
  •  生来不讨喜
    2020-12-01 09:55

    First of all, full credit to ccwasden for the best answer. I had to modify it slightly to make it work for me, so I'm answering this question hoping someone else will find it useful as well.

    Here's what I ended up with (tested on iOS 14 GM with Xcode 12 GM)

    struct SwiftUIView: View {
        @State private var selection = 0
    
        var body: some View {
            Picker(selection: $selection, label: Text("Some Label")) {
                ForEach(0 ..< 5) {
                    Text("Number \($0)") }
            }.onChange(of: selection) { _ in
                print(selection)
            }
            
        }
    }
    

    The inclusion of the "_ in" was what I needed. Without it, I got the error "Cannot convert value of type 'Int' to expected argument type '()'"

提交回复
热议问题