简体   繁体   中英

Convert String to Binding<String> in Swift

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM