问题描述
您好,我在这里遇到了一个问题,在 ios13 或 ios14 上运行时,我的 .sheet() 视图之间没有一致的行为
Hello I am running into a problem here and I do not have a consistent behavior between my .sheet() view when running on ios13 or ios14
我有这样的看法:
@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 click ->设置标签 ->呼叫表 ->显示A标签"在文本视图中.
On ios 13 this work as expected btn click -> set label -> call sheet -> display "A label" in a Text view.
在 ios14 上,我在工作表关闭时在 self.label 中得到一个空字符串,因此它不显示任何内容.
On ios14 I got an empty string in self.label when in sheet closure, hence it does not display anything.
我错过了什么吗?这是 iOS 14 的错误还是我在 ios13 上的错误并得到了纠正.
Did I missed something ? Is it an iOS 14 bug or did I had it wrong on ios13 and that got corrected.
PS:我在我简化的闭包中传递了一些其他变量.
PS: I have a couple of other variables that are passed in the closure I simplified it.
推荐答案
您的代码期望视图更新/创建顺序,但通常它是未定义的(并且可能在 iOS 14 中更改).
Your code have expectation of view update/creation order, but in general it is undefined (and probably changed in iOS 14).
有明确的方式在工作表内传递信息 - 使用不同的工作表创建者,即..sheet(item:...
There is explicit way to pass information inside sheet - use different sheet creator, ie. .sheet(item:...
这是一个可靠的例子.使用 Xcode 12/iOS 14 测试
Here is working reliable example. Tested with 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)
}
}
}
这篇关于SwiftUI @State 和 .sheet() ios13 与 ios14的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!