[英]Reset binding variable in SwiftUI
When if we pass in a binding variable (like $saveDialog as true) to alert or sheet, the variable will reset to false after that.如果我们将绑定变量(如 $saveDialog 为 true)传递给 alert 或 sheet,之后该变量将重置为 false。
.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:但是如果我们想做同样的事情怎么办:当我们点击按钮时清除屏幕,通过将 $clear 设置为 true:
Button("Clear") { self.clear = true }
Then然后
DrawView(clear:$clear)
And in DrawView在 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.问题是:在视图更新期间修改 state,这将导致未定义的行为。 Where do I set the clear variable to false?我在哪里将 clear 变量设置为 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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.