10

I have a textfield, and I am trying to goto another view when user input a specific string.

import SwiftUI

struct ContentView: View {
    @State var whether_go = "No"
    var body: some View {
                    TextField("Goto?", text: $whether_go)
                        .navigate(to: CircleImage(), when: whether_go == "Yes")
    }
}

This will raise error: Cannot convert value of type 'Bool' to expected argument type 'Binding<Bool>' Because when argument need a Binding<Bool>

I tried to use

when: Binding<Bool>(get: whether_happy == "Yes"))

This raise another error: No exact matches in call to initializer.

So what should I do to convert a boolean to Binding<Bool>?

0

1 Answer 1

16

You need to use the Binding(get:set:) initialiser.

var body: some View {
        let binding = Binding<Bool>(get: { self.whether_go == "YES" }, set: { if $0 { self.whether_go = "YES"} else { self.whether_go = "NO" }})
        return TextField("Goto?", text: $whether_go)
                        .navigate(to: CircleImage(), when: binding)
    }

If you want the Binding to be 1-way, simply pass in an empty closure to set.

let binding = Binding<Bool>(get: { self.whether_go == "YES" }, set: { _ in })

Unrelated to your question, but why is whether_go a String and not a Bool? Also, you should follow Swift naming convention, which is lowerCamelCase for variable names (whetherGo).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. whether_go is not the original variable name, I changed this name to make is comprehensible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.