Observing Binding or State variables

心不动则不痛 提交于 2020-05-13 23:28:03

问题


I'm looking for a way of observing @State or @Binding value changes in onReceive. I can't make it work, and I suspect it's not possible, but maybe there's a way of transforming them to Publisher or something while at the same time keeping the source updating value as it's doing right now?

Below you can find some context why I need this:

I have a parent view which is supposed to display half modal based on this library: https://github.com/AndreaMiotto/PartialSheet

For this purpose, I've created a @State private var modalPresented: Bool = false and I'm using it to show and hide this modal view. This works fine, but my parent initializes this modal immediately after initializing self, so I completely loose the onAppear and onDisappear modifiers. The problem is that I need onAppear to perform some data fetching every time this modal is being presented (ideally I'd also cancel network task when modal is being dismissed).


回答1:


use ObservableObject / ObservedObject instead.

an example

import SwiftUI

class Model: ObservableObject {
    @Published var txt = ""
    @Published var editing = false
}

struct ContentView: View {

    @ObservedObject var model = Model()

    var body: some View {
        TextField("Email", text: self.$model.txt, onEditingChanged: { edit in
            self.model.editing = edit
        }).onReceive(model.$txt) { (output) in
            print("txt:", output)
        }.onReceive(model.$editing) { (output) in
            print("editing:", output)
        }.padding().border(Color.red)
    }
}


来源:https://stackoverflow.com/questions/60722806/observing-binding-or-state-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!