自从升级到Xcode 12 / iOS 14以来,我遇到了一些奇怪的行为。为了验证这个行为,我将其隔离在一个测试应用程序中。
在我的原始应用程序中,我有多个Sheet
需要控制。这就是为什么我有一个enum
来区分当前活动的Sheet
,并将其存储在@State private var activeSheet
中。在@ViewBuilder
函数sheetContent()
中,我返回所选Sheet
的View
。
出于简单起见,对于这个测试应用程序,我只实现了一个单独的Sheet
。
这是ContentView
的代码:
struct ContentView: View {
@State private var showingSheet = false
@State private var activeSheet = ContentViewSheets.State.none
var body: some View {
Button(action: {
activeSheet = .aSheet
showingSheet = true // <-- ISSUE: activeSheet is still set to .none here!
}) {
Text("Open Sheet")
}
.sheet(isPresented: $showingSheet, content: sheetContent)
}
@ViewBuilder
private func sheetContent() -> some View {
switch activeSheet {
case .aSheet:
Text("I'm the right sheet!")
case .none:
Text("Oops! I'm not supposed to show up!")
}
}
}
这是枚举的代码:
class ContentViewSheets {
enum State {
case aSheet
case none
}
}
如上所述,ContentView代码中的activeSheet
属性值从未更改为.aSheet
,而是保持为.none
- 因此会显示错误的表格。
这是一个错误还是我没有正确理解苹果的@State
?他们在文档中只写到不应在初始化器中使用它,而仅应在body
内使用,我确实这样做了。