Most of the solutions I see are partaining to SwiftUI where a string can be passed as a Binding String like this
TextField("", $text)
But in this case, it's purely on Swift... I have this code below
final class Coordinator: NSObject, UITextViewDelegate {
var text: Binding<String>
init(text: Binding<String>) {
self.text = text
}
func myFunc(){
let string = "my string" // a dynamically created String
self.text = string // This throws an error that I cannot assign value type of string to Binding<String>
}
}
How can I get to convert String
to Binding<String>
?
CodePudding user response:
The name Coordinator
suggests that we are talking about UIViewRepresentable
.
If so the usual way is to declare the Binding in the UIViewRepresentable
struct and pass the MyView
instance to the coordinator to have access to it
struct MyView: UIViewRepresentable
{
@Binding var text: String
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
...
final class Coordinator: NSObject, UITextViewDelegate {
var parent: MyView
init(_ parent: MyView) {
self.parent = parent
}
func myFunc(){
let string = "my string" // a dynamically created String
parent.text = string
}
}