简体   繁体   English

重置 SwiftUI 中的绑定变量

[英]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.

相关问题 SwiftUI:将@Binding 与来自协议的@Property 变量一起使用 - SwiftUI: Using @Binding with @Property variable from a protocol 如何在 SwiftUI 中初始化 Binding : Bool 变量? - How to initialize a Binding : Bool variable in SwiftUI? 将 @Binding 变量从协议 var 传递给 SwiftUI 中的 if - Passing @Binding variable from protocol var to if in SwiftUI 当变量嵌套在对象中时,如何使用 SwiftUI 将绑定传递给子视图? - How to pass binding to subview with SwiftUI when the variable is nested in an object? SwiftUI:从json分配绑定变量解析object - SwiftUI: assign binding variable from json parsed object 如何在 SwiftUI 中使用带有绑定参数的可选 @State 变量 - How to use optional @State variable with binding parameter in SwiftUI 集成 UIKit 的 SwiftUI 中 @Binding 变量的奇怪行为(iOS 应用程序) - Strange behavior of @Binding variable in SwiftUI integrating UIKit (iOS app) SwiftUI:如何使用@Binding 更新 [struct] 的变量数组? - SwiftUI: How can I update an array of [struct]'s variable with a @Binding? SwiftUI NavigationLink 与基于字典的自定义绑定无法在转换回来后重置 - SwiftUI NavigationLink with custom binding based on dictionary fails to reset after transitioning back SwiftUI - 组合:在 SwiftUI 中绑定主题 - SwiftUI - Combine: Binding Subject in SwiftUI
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM