SwiftUI @State and .sheet() ios13 vs 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)
}
}

在ios 13上,这项工作如预期btn点击->设置标签->呼叫单->显示";标签";在文本视图中。

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

我错过什么了吗?这是iOS 14的错误,还是我在iOS 13上弄错了,然后得到了纠正。

PS:我在闭包中传递了几个其他变量,我简化了它

您的代码期望视图更新/创建顺序,但通常它是未定义的(可能在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)
}
}
}

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

使用这里的另一个答案和这个线程上的注释,我使用@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 ?? "") }
}
}
}

最新更新