0

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>?

3
  • 1
    Binding is only for SwiftUI Views, it doesn't work in a class, leave it in the parent Commented Jan 30, 2023 at 22:47
  • This is a custom TextField in SwiftUI, so the other end of the data binding is coming from a SwiftUI page... My purpose of doing this is that I want to be able to edit some of the text as the user is typing and display it back to the user. Commented Jan 31, 2023 at 5:37
  • Look into using @Published in a class that conforms to ObservableObject, this is probably what you want. Commented Jan 31, 2023 at 7:35

1 Answer 1

1

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.