Reputation: 362
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.
Upvotes: 1
Views: 280
Reputation: 258117
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
}
Upvotes: 2