SwiftUI @State 和 .sheet() ios13 与 ios14

Fit*_*ill 9 ios13 swiftui ios14

您好,我在这里遇到了一个问题,在 ios13 或 ios14 上运行时,我的 .sheet() 视图之间没有一致的行为

我有这样的看法:

@State private var label: String = "" 
@State private var sheetDisplayed = false
///Some code
var body: some View {
   VStack {
      Button(action: {
         self.label = "A label"
         self.isDisplayed = true
      }) {
           Text("test")
       }
   }.sheet(isPresented: $sheetDisplayed, onDismiss: {
        self.label = ""
    }) {
        Text(self.label)
       }
 }
Run Code Online (Sandbox Code Playgroud)

在 ios 13 上,这项工作按预期进行 btn 单击 -> 设置标签 -> 调用表 -> 在文本视图中显示“A 标签”。

在 ios14 上,我在工作表关闭时在 self.label 中得到一个空字符串,因此它不显示任何内容。

我错过了什么吗?这是 iOS 14 的错误还是我在 ios13 上弄错了并得到了纠正。

PS:我有几个其他变量在我简化的闭包中传递。

Asp*_*eri 7

您的代码期望视图更新/创建顺序,但通常它是未定义的(并且可能在 iOS 14 中更改)。

有明确的方式在工作表内传递信息 - 使用不同的工作表创建者,即。 .sheet(item:...

这是工作可靠的例子。使用 Xcode 12 / iOS 14 测试

struct ContentView: View {
    @State private var item: Item?

    struct Item: Identifiable {
        let id = UUID()
        var label: String = ""
    }

    var body: some View {
        VStack {
            Button(action: {
                self.item = Item(label: "A label")
            }) {
                Text("test")
            }
        }.sheet(item: $item, onDismiss: {
            self.item = nil
        }) {
            Text($0.label)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)