我包含了存根代码示例。我不知道怎样才能使这个报告生效。我的期望是,当评估表单呈现闭包时,aDependency
应该是非nil。然而,正在发生的是aDependency
被视为nil,而TheNextView
从未被放在屏幕上。
我如何对TheNextView
进行建模?我遗漏了什么?
struct ADependency {}
struct AModel {
func buildDependencyForNextExperience() -> ADependency? {
return ADependency()
}
}
struct ATestView_PresentationOccursButNextViewNotShown: View {
@State private var aDependency: ADependency?
@State private var isPresenting = false
@State private var wantsPresent = false {
didSet {
aDependency = model.buildDependencyForNextExperience()
isPresenting = true
}
}
private let model = AModel()
var body: some View {
Text("Tap to present")
.onTapGesture {
wantsPresent = true
}
.sheet(isPresented: $isPresenting, content: {
if let dependency = aDependency {
// Never executed
TheNextView(aDependency: dependency)
}
})
}
}
struct TheNextView: View {
let aDependency: ADependency
init(aDependency: ADependency) {
self.aDependency = aDependency
}
var body: some View {
Text("Next Screen")
}
}
这是iOS 14中常见的问题。sheet(isPresented:)
在第一次渲染时被评估,然后没有正确更新。
sheet(item:)
。唯一的问题是你的项目必须符合Identifiable
。
以下版本的代码可以工作:
struct ADependency : Identifiable {
var id = UUID()
}
struct AModel {
func buildDependencyForNextExperience() -> ADependency? {
return ADependency()
}
}
struct ContentView: View {
@State private var aDependency: ADependency?
private let model = AModel()
var body: some View {
Text("Tap to present")
.onTapGesture {
aDependency = model.buildDependencyForNextExperience()
}
.sheet(item: $aDependency, content: { (item) in
TheNextView(aDependency: item)
})
}
}