iosswiftui

How to use ignoresSafeArea with a sheet?


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):


Solution

  • IMO, this could be a SwiftUI bug, you can try these workarounds:

    1. Replace the VStack with a ScrollView:
    var body: some View {
        NavigationStack {
            ScrollView {
                ...
            }
            .ignoresSafeArea(.keyboard)
        }
    }
    
    1. Or using GeometryReader:
    var body: some View {
        NavigationStack {
            GeometryReader { _ in
                VStack {
                    ...
                }
                .ignoresSafeArea(.keyboard)
            }
        }
    }