When if we pass in a binding variable (like $saveDialog as true) to alert or sheet, the variable will reset to false after that.
.alert(isPresented: $saveDialog) {}
But what if we want to do the same thing: says clear the screen when we tap on the button, by setting the $clear to true:
Button("Clear") { self.clear = true }
Then
DrawView(clear:$clear)
And in DrawView
struct DrawView: UIViewRepresentable {
@Binding var clear:Bool
func updateUIView(_ canvas: PKCanvasView, context: Context) {
if clear {
canvas.drawing = PKDrawing()
self.clear = false // Issue
}
}
The issue is: Modifying state during view update, this will cause undefined behavior. Where do I set the clear variable to false?
Here is possible solution
func updateUIView(_ canvas: PKCanvasView, context: Context) {
if clear {
canvas.drawing = PKDrawing()
// make on next event loop, so do not affect current update
// which already uses `clear` state, thus avoid cycling
DispatchQueue.main.async {
self.clear = false
}
}
}
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.