SwiftUI Picker onChange or equivalent?

后端 未结 7 1801
南旧
南旧 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:57

    SwiftUI 1 & 2

    Use onReceive and Just:

    import Combine
    import SwiftUI
    
    struct ContentView: View {
        @State private var selection = 0
    
        var body: some View {
            Picker("Some Label", selection: $selection) {
                ForEach(0 ..< 5, id: \.self) {
                    Text("Number \($0)")
                }
            }
            .onReceive(Just(selection)) {
                print("Selected: \($0)")
            }
        }
    }
    

提交回复
热议问题