【发布时间】:2021-01-24 19:19:30
【问题描述】:
我有一个使用ForEach 列出数组的简单视图。列表中的每个项目都有一个上下文菜单,用于捕获对象并为该对象设置工作表。但是,它的初始执行不会设置状态,而后续执行会设置状态。
这是一个说明问题的简短程序:
struct MyTestView : View {
var people = ["A", "B", "C", "D"]
@State var collectedPerson = "Initial"
@State var showingActionSheet = false
var body : some View {
List {
ForEach(self.people, id: \.self) { person in
Text(person)
.contextMenu {
Button("Edit \(person)") { // person is correct here
self.collectedPerson = person
self.showingActionSheet = true
}
}
.sheet(isPresented: self.$showingActionSheet) {
Text(self.collectedPerson) // State is not set the first time
}
}
}
}
}
最初,屏幕加载“Initial”,这是不正确的:
如果我再次拉起上下文菜单,这一次,状态设置正确(假设我在 B 上拉起上下文菜单):
有谁知道为什么初始状态似乎没有设置?
【问题讨论】:
-
看起来
.sheet(isPresented:)在 iOS 14 中的创建方式有所不同。这是否回答了您的问题? iOS14 introducing errors with @State bindings -
就是这样!谢谢!