Skip to content

Instantly share code, notes, and snippets.

@Tprezioso
Last active September 7, 2023 12:48
Show Gist options
  • Save Tprezioso/5ab24d39898d4f764a5410344edc01aa to your computer and use it in GitHub Desktop.
Save Tprezioso/5ab24d39898d4f764a5410344edc01aa to your computer and use it in GitHub Desktop.
SwiftUI Toast Message modifier
struct ToastDataModel {
var title:String
var image: String
}
struct ToastModifier : ViewModifier {
@Binding var show: Bool
let dataModel: ToastDataModel
func body(content: Content) -> some View {
ZStack {
content
if show {
VStack {
HStack {
Image(systemName: dataModel.image)
Text(dataModel.title)
}.font(.headline)
.foregroundColor(.primary)
.padding([.top,.bottom],20)
.padding([.leading,.trailing],40)
.background(Color(UIColor.secondarySystemBackground))
.clipShape(Capsule())
Spacer()
}
.frame(width: UIScreen.main.bounds.width / 1.25)
.transition(AnyTransition.move(edge: .top).combined(with: .opacity))
.onTapGesture {
withAnimation {
self.show = false
}
}
// Below is for a timed dismissing of the Toast View
// .onAppear(perform: {
// DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
// withAnimation {
// self.show = false
// }
// }
// })
}
}
}
}
extension View {
func toast(toastView: ToastDataModel, show: Binding<Bool>) -> some View {
self.modifier(ToastModifier.init(show: show, dataModel: toastView))
}
}
struct ToastModifier : ViewModifier {
@Binding var show: Bool
var isShowingFromTop: Bool
var toastView: AnyView
func body(content: Content) -> some View {
ZStack {
content
if show {
VStack {
if isShowingFromTop {
toastView
Spacer()
} else {
Spacer()
toastView
}
}
.frame(width: UIScreen.main.bounds.width / 1.25)
.transition(AnyTransition.move(edge: isShowingFromTop ? .top : .bottom).combined(with: .opacity))
.onTapGesture {
withAnimation {
self.show = false
}
}
// Below is for a timed dismissing of the Toast View
// .onAppear(perform: {
// DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
// withAnimation {
// self.show = false
// }
// }
// })
}
}
}
}
extension View {
func toast(show: Binding<Bool>, isShowingFromTop: Bool = false, toastView: @escaping () -> any View) -> some View {
self.modifier(ToastModifier.init(show: show, isShowingFromTop: isShowingFromTop, toastView: AnyView(toastView())))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment