SwiftUI @State 和 .sheet() ios13 对比 ios14

SwiftUI @State and .sheet() ios13 vs ios14

你好,我 运行 遇到了一个问题,当 ios13 或 运行 时,我的 .sheet() 视图之间没有一致的行为=28=]

我看到了这样的景色:

@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)
       }
 }

在 ios 13 上按预期工作 btn 单击 -> 设置标签 -> 调用 sheet -> 在文本视图中显示“标签”。

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

我错过了什么吗?这是一个 iOS 14 错误还是我在 ios13 上弄错了并且已更正。

PS:我在闭包中传递了几个其他变量,我对其进行了简化。

您的代码期望查看 update/creation 顺序,但通常它是未定义的(并且可能在 iOS 14 中更改)。

有明确的方式在 sheet 中传递信息 - 使用不同的 sheet 创建者,即。 .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([=10=].label)
        }
    }
}

这在 iOS 14 中是一些非常奇怪的行为,似乎没有记录在案。

使用 here and the comment on this thread,我使用 @Binding 来解决问题,因为它似乎是最干净和最 SwiftUI-esq 的解决方案。

我不知道为什么这种行为发生了变化,而且它似乎不如以前直观,所以我假设它是一个错误!

一个例子:

struct MainView: View {
    @State private var message = ""
    @State private var showSheet = false

    var body: some View {
        Button(action: {
            self.message = "This will display the correct message"
            self.showSheet = true
        }, label: {
            Text("Test Button")
        })
        .sheet(isPresented: self.$showSheet) {
            SheetView(message: self.$message)
        }
    }
}

struct SheetView: View {
    @Binding var message: Int

    var body: some View {
        Text(self.message)
    }
}

SwiftUI 2.0 的行为发生了变化,因此它也会影响 MacOS 11,即使从未使用该绑定,只需向视图添加绑定即可修复它,这让我认为这是一个实现错误。 此外,仅在视图主体内的 Text() 中使用 details 状态变量也可以修复它。

struct MyViewController : View {

    @State var details: String?
    @State var showDetails = false

    //    @Binding var havingAbindingFixesIt: String?

    var body: some View {
        VStack {
            //            Text(details ?? "")
            Text("Tap here for details")
                .onTapGesture {
                    self.details = "These are the details"
                    self.showDetails.toggle()
                }
                .sheet(isPresented: $showDetails) { Text(details ?? "") }
        }
    }
}