Skip to content

Instantly share code, notes, and snippets.

@andrew-codechimp
Created September 5, 2020 16:16
Show Gist options
  • Save andrew-codechimp/851da691a0b4363e144d88746382a724 to your computer and use it in GitHub Desktop.
Save andrew-codechimp/851da691a0b4363e144d88746382a724 to your computer and use it in GitHub Desktop.
//
// DismissableView.swift
//
// Created by Andrew Jackson on 05/09/2020.
//
import SwiftUI
struct DismissableView<Content: View>: View {
let color: Color
let content: () -> Content
let onDismiss: () -> Void
func onDismiss(_ callback: @escaping () -> ()) -> DismissableView {
DismissableView(color: color, content: content, onDismiss: callback)
}
func color(_ color: Color) -> DismissableView {
DismissableView(color: color, content: content)
}
public init(@ViewBuilder content: @escaping () -> Content) {
self.color = Color(.systemGray4)
self.content = content
self.onDismiss = {}
}
public init(color: Color, @ViewBuilder content: @escaping () -> Content) {
self.color = color
self.content = content
self.onDismiss = {}
}
public init(color: Color, @ViewBuilder content: @escaping () -> Content, onDismiss: @escaping () -> Void) {
self.color = color
self.content = content
self.onDismiss = onDismiss
}
var body: some View {
VStack(alignment: .leading) {
HStack(alignment: .top) {
self.content()
Spacer()
Image(systemName: "multiply.circle.fill")
.foregroundColor(.gray)
.frame(width: 20)
.onTapGesture {
self.onDismiss()
}
}
.padding(15)
}
.background(
RoundedRectangle(cornerRadius: 12, style: .continuous)
.fill(color)
)
}
}
struct DismissableHintView_Previews: PreviewProvider {
static var previews: some View {
let hintText = "A generic dismissable view that puts an X in the top trailing corner.\nThe onDismiss method is called when the X is pressed.\nYou can optionally change the background color."
Group {
VStack {
DismissableView(color: Color(.systemTeal), content: { Text(hintText) })
.onDismiss {
// Do something
}
.environment(\.colorScheme, .light)
.padding()
Spacer()
}
VStack {
DismissableView() {
Text(hintText)
}
.color(Color(.systemGray4))
.environment(\.colorScheme, .dark)
.padding()
Spacer()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment