Search code examples
swiftuiswiftui-sheet

Why can't I close a sheet view when in landscape?


When I create a .sheet view and turn the iPhone to landscape, I can't close it.

I tried swiping down from the top but the sheet is just stuck there.

Example code:

import SwiftUI

struct ContentView: View {
    @State var sheet = false
    var body: some View {
        VStack {
            Button("Open da sheeeet") {
                sheet = true
            }
        }
        .sheet(isPresented: $sheet) {
            Text("you are stuck now ahahahhahah\n(if youre in landscape)")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Any help Appreciated!

iOS 16.4, XCode 14.3.1


Solution

  • By default, the sheet doesn't automatically adapt to landscape mode. So, you need to add a close button on custom sheet. like :

    struct CustomSheetView: View {
        @State private var isSheetPresented = false
    
        var body: some View {
            Button("Show Sheet") {
                isSheetPresented = true
            }
            .sheet(isPresented: $isSheetPresented) {
                SheetView(isSheetPresented: $isSheetPresented)
                    .ignoresSafeArea(.all)
            }
        }
    }
    
    struct SheetView: View {
        @Binding var isSheetPresented: Bool
    
        var body: some View {
            VStack {
                Text("you are stuck now ahahahhahah\n(if youre in landscape)")
                Button("Close") {
                    isSheetPresented = false
                }
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.white)
            .edgesIgnoringSafeArea(.all)
        }
    }