简体   繁体   中英

SwiftUI - How do I run code from the Coordinator of another Struct from a function inside a VStack?

I am new to SwiftUI. I am using it for just one day.

I have this:

struct Canvas: UIViewRepresentable {

  class Coordinator:NSObject, PKCanvasViewDelegate {
    func scrollViewDidZoom(_ scrollView: UIScrollView) {
      doSomething(scrollView)
    }
    
    func doSomething(_ scrollView: UIScrollView) {
      // do something with the scrollView
      // change the scrollView size and content area
    }
  }

  func makeUIView(context: Context) -> PKCanvasView {
    canvasView.tool = PKInkingTool(.pen, color: .black, width: 15)
    canvasView.isOpaque = false
    canvasView.backgroundColor = UIColor.clear
    canvasView.delegate = context.coordinator
    return canvasView
  }

Before the last line of makeUIView , that belongs to the struct Canvas , I want to execute doSomething(scrollView)

The problem is that canvasView is still being created and its bounds are equal to (0,0,0,0) , so doSomething() will fail.

So I have to call it from the time I create the view, inside .onAppear , something like this:

struct ContentView: View {
  @Environment(\.undoManager) var undoManager
  @State private var canvasView = PKCanvasView()
    
  var toolBar:Toolbar {
    var toolBar = Toolbar()
    toolBar.canvasView = canvasView
    return toolBar
  }

  var canvas:Canvas {
    return Canvas(canvasView: $canvasView)
  }
  
  var body: some View {
    VStack(alignment:.center, spacing: 10) {
      toolBar
      Spacer().frame(height: 1)
      Divider()
      canvas
    }

    .onAppear {
      // execute doSomething() here
    }
  }
}

how?

Please answer me as I am 5 years old in terms of SwiftUI. My brain is still spinning with all this knew knowledge. Ok, make it 3 years old.

Here is possible approach (it worked for me in many scenarios)

  func makeUIView(context: Context) -> PKCanvasView {
    canvasView.tool = PKInkingTool(.pen, color: .black, width: 15)
    canvasView.isOpaque = false
    canvasView.backgroundColor = UIColor.clear
    canvasView.delegate = context.coordinator
   
    DispatchQueue.main.async {
       // in this time created view is already in view hierarchy
       // so can be processed somehow

       context.coordinator.doSomething(canvasView)  // << try this !!
    }
    return canvasView
  }

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