SwiftUI Picker onChange or equivalent?

后端 未结 7 1804
南旧
南旧 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 10:02

    Here is what I just decided to use... (deployment target iOS 13)

    struct MyPicker: View {
        @State private var favoriteColor = 0
    
        var body: some View {
            Picker(selection: $favoriteColor.onChange(colorChange), label: Text("Color")) {
                Text("Red").tag(0)
                Text("Green").tag(1)
                Text("Blue").tag(2)
            }
        }
    
        func colorChange(_ tag: Int) {
            print("Color tag: \(tag)")
        }
    }
    

    Using this helper

    extension Binding {
        func onChange(_ handler: @escaping (Value) -> Void) -> Binding {
            return Binding(
                get: { self.wrappedValue },
                set: { selection in
                    self.wrappedValue = selection
                    handler(selection)
            })
        }
    }
    

    EDIT:

    If your deployment target is set to iOS 14 or higher -- Apple has provided a built in onChange extension to View, which can be used like this instead (Thanks @Jeremy):

    Picker(selection: $favoriteColor, label: Text("Color")) {
        // ..
    }
    .onChange(of: favoriteColor) { print("Color tag: \($0)") }
    

提交回复
热议问题