Rillieux
Rillieux

Reputation: 707

How do I dismiss this custom modal using bindings?

I cannot figure out how to dismiss a view that is showing inside its parents by way of a @State var showingCardModal = false. Here is the code for my ContentView:

import SwiftUI

struct ContentView: View {

    @State var showingCardModal = false

    var body: some View {

        ZStack {
            Button(action: {
                withAnimation {
                self.showingCardModal.toggle()
                }
            }) {
                Text("Show").font(.headline)
            }
            .frame(width: 270, height: 64)
            .background(Color.secondary).foregroundColor(.white)
            .cornerRadius(12)
            if showingCardModal {
                CardModal()
                    .transition(AnyTransition.scale.combined(with: .opacity).animation(.easeIn(duration: 0.75)))
            }
        }
    }
}

And for the CardModal inside of it:

import SwiftUI

struct CardModal: View {

    //@Binding var isPresented: Bool

    var body: some View {

        ZStack{
            Color(.secondarySystemBackground).edgesIgnoringSafeArea(.all)
            VStack{
                Spacer().frame(height:30)
                Text("Today, 20 March").font(.title)
                Spacer()
                }
            CarouselView(itemHeight: 420, views: [
                SingleCard(name: "Card 1", contentOpacity: 1.0),
                SingleCard(name: "Card 2", contentOpacity: 1.0),
                SingleCard(name: "Card 3", contentOpacity: 1.0),
                SingleCard(name: "Card 4", contentOpacity: 1.0),
                SingleCard(name: "Card 5", contentOpacity: 1.0),
                SingleCard(name: "Card 6", contentOpacity: 1.0),
                SingleCard(name: "Card 7", contentOpacity: 1.0),
                ])
            VStack {
                Spacer()
                Button(action:{}) {
                    Text("Done").font(.headline).foregroundColor(.purple)
                    }
                    .frame(width: 300, height: 48)
                    .background(Color.gray.opacity(0.25))
                    .cornerRadius(12)
                Spacer().frame(height: 20)
            }
        }
    }
}

I'm trying to replicate somewthing like in the Health App when a modal slides in from the bottom for the symptoms of a menstral cycle. THe modal is full screen and is dismissed with a button.

Upvotes: 1

Views: 80

Answers (1)

Asperi
Asperi

Reputation: 257711

It can be like this...

struct CardModal: View {
    @Binding var isPresented: Bool
...

    Button(action:{ self.isPresented = false }) {

and in ContentView

if showingCardModal {
    CardModal(isPresented: self.$showingCardModal)

and in PreviewProvider

CardModal(isPresented: .constant(true))

Upvotes: 1

Related Questions