如何解决SwiftUI @State和.sheetiOS13与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单击->设置标签->调用表->在“文本”视图中显示“ A标签”。
在ios14上,我在工作表关闭时在self.label中有一个空字符串,因此它不显示任何内容。
我错过了什么吗?是iOS 14的错误,还是我在ios13上将其弄错了,并且已得到纠正。
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中一些非常奇怪的行为,似乎没有记录。
在这里使用other answer和对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 ?? "") }
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。