Why does the main view shift upward when a text field within a sheet becomes focused? To me, it appears visually incorrect regardless of the context, and applying .ignoresSafeArea(.keyboard)
to the VStack
doesn't seem to resolve the issue.
struct ContentView: View {
let colors: [Color] = [.green, .red, .blue, .pink, .purple]
@State private var sheetShown = false
@State private var q = ""
var body: some View {
NavigationStack {
VStack {
ForEach(colors, id: \.self) { color in
Rectangle()
.fill(color)
.frame(height: 120)
}
Spacer()
Button { sheetShown = true }
label: { Text("Show Sheet") }
.buttonStyle(.borderedProminent)
}
.ignoresSafeArea(.keyboard)
.padding()
}
.sheet(isPresented: $sheetShown) {
VStack {
Text("hello")
TextField("Search", text: $q)
}
}
}
}
#Preview {
ContentView()
}
Without focus on the input:
With focus on the input (see green Rectangle sticking out from above):
IMO, this could be a SwiftUI bug, you can try these workarounds:
ScrollView
:var body: some View {
NavigationStack {
ScrollView {
...
}
.ignoresSafeArea(.keyboard)
}
}
GeometryReader
:var body: some View {
NavigationStack {
GeometryReader { _ in
VStack {
...
}
.ignoresSafeArea(.keyboard)
}
}
}