Home > database >  SwiftUI: ViewModel string to binding child view data
SwiftUI: ViewModel string to binding child view data

Time:10-12

I have this view model string that I have like to pass to a child view with a binding string.

struct Beginner: View {
  
  @StateObject var vm: BeginnerViewModel = BeginnerViewModel()
      
  var body: some View {
    VStack {
      ForEach(vm.posts!, id: \.id) { post in
        VStack(alignment: .leading, spacing: 10) {
          WebView(text: post.tweet)
            .frame(width: 700, height: 400).offset(x: 140)
        }
      }
    }
  }
}

struct WebView: UIViewRepresentable {
  @Binding var text: String
   
  func makeUIView(context: Context) -> WKWebView {
    return WKWebView()
  }
   
  func updateUIView(_ uiView: WKWebView, context: Context) {
    uiView.loadHTMLString(text, baseURL: nil)
  }
}

In the line WebView(text: post.tweet), there is this error message saying:

Cannot convert value of type 'String' to expected argument type 'Binding<String>'

What is the correct way to pass the data to the webview? Any help will be greatly appreciated.

CodePudding user response:

It seems you don't need binding in WebView, so use just

struct WebView: UIViewRepresentable {
  var text: String                      // << this !!

  // ... other code
}
  • Related