Reputation: 327
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>?
Upvotes: 10
Views: 6131
Reputation: 54706
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
).
Upvotes: 16