Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Manipulating binding variables in SwiftUI

Suppose I have a string that’s binding:

@Binding var string: String

But, I want to manipulate that string, and then pass it to a child view.

struct ViewOne: View {
    @State var string: String = "Hello"
    
    var body: some View {
        ViewTwo(string: string + " World") // this is invalid, as ViewTwo requires Binding<String>
    }
}

struct ViewTwo: View {
    @Binding var string: String
    
    var body: some View {
        Text(string)
    }
}

How should I go about manipulating that string, such that it will update the UI when the state changes? Let’s assume that I want to re-use ViewTwo for different components, and so I would want to manipulate the string before it is passed to the view.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A computed variable doesn’t work, as it isn’t Binding

private var fixedString: String {
    return string + " World"
}

And I don’t want to create a binding variable, because the setter makes no sense in this context

private var fixedString: Binding<String> {
    Binding<String> (
        get: {
            string + " World"
        }, set: {
            // this function doesn't make sense here - how would it update the original variable?
        }
    )
}

Am I just using @State and @Binding wrong?

>Solution :

Just remove the @Binding inside ViewTwo:

struct ViewTwo: View {
    var string: String /// no need for the `@Binding`!
    
    var body: some View {
        Text(string)
    }
}

SwiftUI will update ViewTwo even if you don’t have the @Binding (it basically re-renders the entire body whenever a @State or @Published var gets changed).

You only need Bindings when you need to update/set the original @State or @Published property. In that case you’d add something like the var fixedString: Binding<String> in your question.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading