Skip to content

Instantly share code, notes, and snippets.

@atetlaw
Last active January 8, 2022 09:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atetlaw/c8dec1d9842750f2136af1844fc88abb to your computer and use it in GitHub Desktop.
Save atetlaw/c8dec1d9842750f2136af1844fc88abb to your computer and use it in GitHub Desktop.
A simple pure SwiftUI card-style action sheet, that also blurs the background content, with animated transition
//
// CardSheet.swift
//
// Created by Andrew Tetlaw on 4/12/21.
//
import SwiftUI
struct CardSheet<SheetContent: View>: ViewModifier {
@Binding var show: Bool
@ViewBuilder let sheetContent: () -> SheetContent
func body(content: Content) -> some View {
ZStack(alignment: .bottom) {
content
if show {
ContainerRelativeShape()
.ignoresSafeArea()
.background(.thinMaterial)
.onTapGesture {
withCardSheetAnimation {
show.toggle()
}
}
sheetContent()
.transition(.opacity.combined(with: .move(edge: .bottom)))
.zIndex(1)
}
}
}
}
extension View {
func cardSheet<SheetContent: View>(show: Binding<Bool>, sheetContent: @escaping () -> SheetContent) -> some View {
modifier(CardSheet(show: show, sheetContent: sheetContent))
}
}
extension Animation {
static var defaultCardSheetAnimation: Animation {
Animation.easeOut(duration: 0.18)
}
}
func withCardSheetAnimation<Result>(_ body: () throws -> Result) rethrows -> Result {
try withAnimation(.defaultCardSheetAnimation, body)
}
@atetlaw
Copy link
Author

atetlaw commented Dec 3, 2021

In your View:

.cardSheet(show: $showNewEntrySheet) {
    NewEntryForm()
}

You need to set the show binding variable using animation, so it slides up from the bottom, and is dismissed by sliding down:

Show:

withCardSheetAnimation {
    show = true
}

Hide:

withCardSheetAnimation {
    show = false
}

It's automatically dismissed by tapping the background.

And it looks like this:
CardSheet

No need to dive into UIKit and do crazy things...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment