2021-01-30

Custom Binding Initialisation with backwards compatible to source of truth

I am initializing my Binding value in my custom way, which is working just fine, Now I like to make this custom initialisation be able to effect the source of truth, how I could possibly make this happen? For giving you more information about what I just said: my BindingView controls the incoming value right in the front door and decide the action with some logic, while this happening my Binding value became in some way unable/forgot to update source of truth, after Initialisation BindingView, ContentView and BindingView have deferent prospective of value! the goal is putting some kind of codes in initializing BindingView to make this happen, to having same value for both Views. thanks for reading and helping.

    import SwiftUI

struct ContentView: View {

    @State private var value: Int = Int()

    var body: some View {

        Text("value of ContentView:" + value.description)
            .padding()

        Button ("update value to 0") {
            
            value = 0
        }
        .padding()

        Button ("update value to 1") {
            
            value = 1
        }
        .padding()

        BindingView(value: $value)
            .padding()
        
    }
    
}



struct BindingView: View {

    @Binding var value: Int

    init(value: Binding<Int>) {

        print("initializing Binding,", "incoming value:", value.wrappedValue.description)

        if value.wrappedValue == 0 {
            
            _value = .constant(100)
 
        }
        else {
            
            _value = value
            
        }
        
        
    }

    var body: some View {

        Text("value of BindingView:" + value.description)

    }
    
}


from Recent Questions - Stack Overflow https://ift.tt/3t2DCbY
https://ift.tt/eA8V8J

No comments:

Post a Comment