swiftswiftuibottom-sheet

Show bottom sheet after button press swiftui


I'm trying to add to my app bottom sheet with responsive height which I can set programmatically. For this purpose I'm trying to use this video. Here is code of my view controller:

struct SecondView: View {
    @State var cardShown = false
    @State var cardDismissal = false
    
    var body: some View {
        Button {
            cardShown.toggle()
            cardDismissal.toggle()
        } label: {
            Text("Show card")
                .bold()
                .foregroundColor(Color.white)
                .background(Color.red)
                .frame(width: 200, height: 50)
        }
        
        BottomCard(cardShown: $cardShown, cardDismissal: $cardDismissal) {
            CardContent()
        }
    }
}

struct CardContent:View{
    var body: some View{
        Text("some text")
    }
}

struct BottomCard<Content:View>:View{
    @Binding var cardShown:Bool
    @Binding var cardDismissal:Bool
    let content:Content
    
    init(cardShown:Binding<Bool> , cardDismissal:Binding<Bool>, @ViewBuilder content: () -> Content){
        _cardShown = cardShown
        _cardDismissal = cardDismissal
        self.content = content()
    }
    
    var body: some View{
        ZStack{
            //Dimmed
            GeometryReader{ _ in
                EmptyView()
            }
            .background(Color.red.opacity(0.2))
            .opacity(cardShown ? 1 : 0)
            .animation(.easeIn)
            .onTapGesture {
                cardShown.toggle()
            }
            
            // Card
            VStack{
                Spacer()
                
                VStack{
                    content
                }
            }
            .edgesIgnoringSafeArea(.all)
        }
    }
}

but after pressing the button I don't see any pushed bottom menu. I checked and it seems that I have similar code to this video but on the video bottom sheet appears. Maybe I missed something important for menu showing. The main purpose is to show bottom menu with responsive height which will wrap elements and will be able to change menu height. I tried to use .sheet() but this element has stable height as I see. I know that from the ios 15+ we will have some solutions for this problem but I would like to create something more stable and convenient :)


Solution

  • iOS 16

    We can have native SwiftUI resizable sheet (like UIKit). This is possible with the new .presentationDetents() modifier.

    .sheet(isPresented: $showBudget) {
        BudgetView()
            .presentationDetents([.height(250), .medium])
            .presentationDragIndicator(.visible)
    }
    
    

    Demo:

    Demo