Anthony
Anthony

Reputation: 890

How to ignore safearea when presenting a sheet?

On devices that have a home indicator (e.g. iPhone 15 Pro), the safe area is being added at the bottom. That displays fine but when the keyboard appears, it's throwing out the view and it appears as though the safeareainset is being divided between the top and bottom of the view (see screenshots). I've made the background yellow to easily see the white padding that is being added. I've tried all sorts of combinations of ignoresSafeArea() and can't get the right solution which is to have no additional padding.

import SwiftUI

struct TestSheetHeight: View {
    
    @State var showCard: Bool = false
    
    var body: some View {
        
        Button(action: {
            showCard.toggle()
        }, label: {
            Text("Show the Card")
        })
        .sheet(isPresented: $showCard, content: {
            CardView()
        })
        
    }
}


struct CardView: View {
    
    @State var height: CGFloat = 0
    @State var textField: String = ""
    
    var body: some View {
        
        VStack {
            Text("Line A")
            Text("Line B")
            Text("Line C")
            TextField(text: $textField) {
                Text("Test")
            }
            .padding(.horizontal)
        }
        .background {
            GeometryReader { geometry in
                Color.yellow
                    .onChange(of: geometry.size) {
                        height = geometry.size.height
                    }
                    .ignoresSafeArea()
            }
        }
        .presentationDetents([.height(height)])
    }
}

iPhone SE without keyboard iPhone SE with keyboard

iPhone 15 Pro without keyboard

iPhone 15 Pro with keyboard

Upvotes: 0

Views: 892

Answers (1)

miltenkot
miltenkot

Reputation: 311

Hey try this CardView implementation. Unfortunately, I don't have an explanation for why setting this inside the background works incorrectly.

struct CardView: View {
    @State var height: CGFloat = 0
    @State var textField: String = ""
    
    var body: some View {
        ZStack {
            Color.yellow.ignoresSafeArea()
            VStack {
                Text("Line A")
                Text("Line B")
                Text("Line C")
                TextField(text: $textField) {
                    Text("Test")
                }
                .padding(.horizontal)
            }
            .background {
                GeometryReader { geometry in
                    Color.clear
                        .onChange(of: geometry.size) {
                            height = geometry.size.height
                        }
                        .ignoresSafeArea()
                }
            }
            .presentationDetents([.height(height)])
        }
    }
}

Upvotes: 0

Related Questions