SwiftUI Can I use Binding get set custom binding with @Binding property wrapper?

筅森魡賤 提交于 2020-08-08 06:15:18

问题


How can I use Binding(get: { }, set: { }) custom binding with @Binding property on SwiftUI view. I have used this custom binding successfully with @State variable but doesn't know how to apply it to @Binding in subview initializer. I need it to observe changes assigned to @Binding property by parent class in order to execute code with some side effects!


回答1:


Here is possible approach. The demo shows two-directional channel through adapter binding between main & dependent views. Due to many possible callback on update there might be needed to introduce redundancy filtering, but that depends of what is really required and out of scope.

Demo code:

struct TestBindingIntercept: View {

    @State var text = "Demo"
    var body: some View {
        VStack {
            Text("Current: \(text)")
            TextField("", text: $text)
                .textFieldStyle(RoundedBorderTextFieldStyle())
            Divider()
            DependentView(value: $text)
        }
    }
}

struct DependentView: View {
    @Binding var value: String

    private var adapterValue: Binding<String> {
        Binding<String>(get: {
            self.willUpdate()
            return self.value
        }, set: {
            self.value = $0
            self.didModify()
        })
    }

    var body: some View {
        VStack {
            Text("In Next: \(adapterValue.wrappedValue)")
            TextField("", text: adapterValue)
                .textFieldStyle(RoundedBorderTextFieldStyle())
        }
    }

    private func willUpdate() {
        print(">> run before UI update")
    }

    private func didModify() {
        print(">> run after local modify")
    }
}

struct TestBindingIntercept_Previews: PreviewProvider {
    static var previews: some View {
        TestBindingIntercept()
    }
}


来源:https://stackoverflow.com/questions/59311887/swiftui-can-i-use-binding-get-set-custom-binding-with-binding-property-wrapper

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