I've encountered a strange bug when a sheet
doesn't open if triggered in onAppear
.
The following does not trigger the sheet
in Xcode 12.3, iOS 14.3:
struct ContentView: View {
@State private var sheetActive = false
var body: some View {
Text("Test")
.sheet(isPresented: $sheetActive) {
Text("Sheet")
}
.onAppear {
sheetActive = true
}
}
}
The sheet
only pops up after I interact with the screen in any way.
However, if I wrap Text
in NavigationView
/ List
etc. it does work.
Also, even attaching a simple modifier (like onChange
) triggers the sheet
:
struct ContentView: View {
@State private var sheetActive = false
var body: some View {
Text("Test")
.sheet(isPresented: $sheetActive) {
Text("Sheet")
}
.onAppear {
sheetActive = true
}
.onChange(of: sheetActive) {
print($0)
}
}
}
It also works when I trigger the sheet
asynchronously:
struct ContentView: View {
@State private var sheetActive = false
var body: some View {
Text("Test")
.sheet(isPresented: $sheetActive) {
Text("Sheet")
}
.onAppear {
DispatchQueue.main.async {
sheetActive = true
}
}
}
}
Is this a bug in iOS 14.3 or some intended change I'm not aware of?
If you change your sheetActive
to true
it should open upon initialization.
The bugs of using onAppear()
to initialize/active stuff are constantly being mentioned in SO and the Apple forums. It is very unreliable.
struct ActiveSheetView: View {
@State private var sheetActive = true
var body: some View {
Text("Test")
.sheet(isPresented: $sheetActive) {
Text("Sheet")
}
}
}