SwiftUI Picker onChange or equivalent?

后端 未结 7 1777
南旧
南旧 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:15

    I use a segmented picker and had a similar requirement. After trying a few things I just used an object that had both an ObservableObjectPublisher and a PassthroughSubject publisher as the selection. That let me satisfy SwiftUI and with an onReceive() I could do other stuff as well.

    // Selector for the base and radix
    Picker("Radix", selection: $base.value) {
        Text("Dec").tag(10)
        Text("Hex").tag(16)
        Text("Oct").tag(8)
    }
    .pickerStyle(SegmentedPickerStyle())
    // receiver for changes in base
    .onReceive(base.publisher, perform: { self.setRadices(base: $0) })
    

    base has both an objectWillChange and a PassthroughSubject<Int, Never> publisher imaginatively called publisher.

    class Observable<T>: ObservableObject, Identifiable {
        let id = UUID()
        let objectWillChange = ObservableObjectPublisher()
        let publisher = PassthroughSubject<T, Never>()
        var value: T {
            willSet { objectWillChange.send() }
            didSet { publisher.send(value) }
        }
    
        init(_ initValue: T) { self.value = initValue }
    }
    
    typealias ObservableInt = Observable<Int>
    

    Defining objectWillChange isn't strictly necessary but when I wrote that I liked to remind myself that it was there.

    0 讨论(0)
提交回复
热议问题