SwiftUI Picker onChange or equivalent?

后端 未结 7 1798
南旧
南旧 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:11

    For people that have to support both iOS 13 and 14, I added an extension which works for both. Don't forget to import Combine.

    Extension View {
        @ViewBuilder func onChangeBackwardsCompatible(of value: T, perform completion: @escaping (T) -> Void) -> some View {
            if #available(iOS 14.0, *) {
                self.onChange(of: value, perform: completion)
            } else {
                self.onReceive([value].publisher.first()) { (value) in
                    completion(value)
                }
            }
        }
    }
    

    Usage:

    Picker(selection: $selectedIndex, label: Text("Color")) {
        Text("Red").tag(0)
        Text("Blue").tag(1)
    }.onChangeBackwardsCompatible(of: selectedIndex) { (newIndex) in
        print("Do something with \(newIndex)")
    }
    

提交回复
热议问题