Ronnie
Ronnie

Reputation: 362

How do I communicate between a SwiftUI view to another when a coordinator is involved?

I am new to SwiftUI. Just a few days trying to learn. I have tried to find a tutorial on this but I was not successfull.

Imagine I have the following view:

Struct MyPicker: View {

MyPicker is inside a VStack inside ContentView. I have to pass, from MyPicker to ContentView, 3 parameters: color, width and type.

The problem is that these values come from a delegate callback inside MyPicker. So I have to have a coordinator inside MyPicker.

struct MyPickerHelper: UIViewRepresentable {
  class Coordinator:NSObject, MyPickerDelegate {
    var color:UIColor
    var width:CGFloat
    var type:PKInkingTool.InkType 

    func toolPickerSelectedToolDidChange(_ toolPicker: PKToolPicker) {
      if toolPicker.selectedTool is PKInkingTool {
        let tool = toolPicker.selectedTool as! PKInkingTool
        self.color = tool.color
        self.width = tool.width
        self.type = tool.inkType
      }
    }

Theare are a lot of stuff like @Binding, @Published, @State, etc. What do I put where to make MyPicker communicate changes to ContentView?

Upvotes: 2

Views: 1133

Answers (1)

Asperi
Asperi

Reputation: 258365

You need to have state as source of truth in parent view and pass binding to it into representable view, which... here is an example for one parameter...

struct MyPicker: View {
   @State private var color: UIColor = .clear   // << source

   var body: some View {
      MyPickerHelper(color: $color)     // << pass binding
   }
}

and now in representable

struct MyPickerHelper: UIViewRepresentable {
  @Binding var color: UIColor

  func makeCoordinator() -> Coordinator {
     Coordinator(owner: self)
  }

  ...

  class Coordinator:NSObject, MyPickerDelegate {
    private var owner: MyPickerHelper

    init(owner: MyPickerHelper) {
      self.owner = owner
    }

    func toolPickerSelectedToolDidChange(_ toolPicker: PKToolPicker) {
      if toolPicker.selectedTool is PKInkingTool {
        let tool = toolPicker.selectedTool as! PKInkingTool

        self.owner.color = tool.color         // << here update via binding !!!
      }
    }

   ...
}

Upvotes: 4

Related Questions