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

左心房为你撑大大i 提交于 2021-01-05 07:05:11

问题


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?


回答1:


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

   ...
}


来源:https://stackoverflow.com/questions/63942629/how-do-i-communicate-between-a-swiftui-view-to-another-when-a-coordinator-is-inv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!