nickcoding
nickcoding

Reputation: 475

Trying to pass a Binding<Bool> variable into a view?

so I have a binding variable that is declared in a class with:

@Binding var variableName: Bool

I am returning a view when a certain function is called. I'd like to pass the annotation into that view with:

return CustomView(variableName: $variableName)

Is this correct? I'm not sure. Also, inside the view itself, I'm not entirely sure how to do the initialization properly. The end goal is to be able to access the value of variableName from the functions of the view. Anyways, I tried declaring the following inside the CustomView class:

@Binding var variableName: Bool

For the initialization, I wasn't sure if I should pass in the variable name into the arguments (and if I should, I wasn't sure how. I also didn't know if I should somehow initialize with self.variableName = value...Just to be clear, the goal is to access the value of variableName after initialization. If I can add any more code to make this more comprehensible, let me know!

Upvotes: 0

Views: 1694

Answers (1)

Cuneyt
Cuneyt

Reputation: 981

It is not really clear what you want to achieve, but have a look at the code below:

import SwiftUI

struct ParentView: View {

    @Binding var customVariable: Bool

    var body: some View {
        VStack {
            Toggle(isOn: $customVariable) {
                Text("Show/Hide Custom View")
            }
            if $customVariable.wrappedValue {
                CustomView(customVariable: $customVariable)
            }
        }
    }
}

struct CustomView: View {

    @Binding var customVariable: Bool

    init(customVariable: Binding<Bool>) { // You don't need an initializer here, it is just to demonstrate how you can use it for Binding values
        _customVariable = customVariable
    }

    var body: some View {
        Text("Custom View")
    }
}

However, a better way to coordinate the model and the view in SwiftUI can be illustrated as below:

import SwiftUI

class CustomModel: ObservableObject {

    @Published var shouldShowCustomView: Bool = false
}    

struct ParentView: View {

    @ObservedObject var model: CustomModel

    var body: some View {
        VStack {
            Toggle(isOn: $model.shouldShowCustomView) {
                Text("Show/Hide Custom View")
            }
            if model.shouldShowCustomView {
                CustomView()
                    .environmentObject(model)
            }
        }
    }
}

struct CustomView: View {

    @EnvironmentObject var model: CustomModel

    var body: some View {
        Text("Custom View")
    }
}

So, instead of Binding, you can use ObservableObject with Published values.

Upvotes: 2

Related Questions