ToastModifier.swift (1195B)
1 import SwiftUI 2 3 struct ToastModifier<Overlay: View>: ViewModifier { 4 @Binding var isPresented: Bool 5 let autoDismiss: Double 6 let overlay: () -> Overlay 7 8 func body(content: Content) -> some View { 9 ZStack { 10 content 11 if isPresented { 12 overlay() 13 .transition(.opacity.combined(with: .scale(scale: 0.98))) 14 .zIndex(1) 15 .onAppear { 16 guard autoDismiss > 0 else { return } 17 DispatchQueue.main.asyncAfter(deadline: .now() + autoDismiss) { 18 withAnimation { isPresented = false } 19 } 20 } 21 } 22 } 23 .animation(.easeInOut(duration: 0.15), value: isPresented) 24 } 25 } 26 27 extension View { 28 func toast<Overlay: View>( 29 isPresented: Binding<Bool>, 30 autoDismiss: Double = 1.2, 31 @ViewBuilder overlay: @escaping () -> Overlay 32 ) -> some View { 33 modifier( 34 ToastModifier( 35 isPresented: isPresented, 36 autoDismiss: autoDismiss, 37 overlay: overlay 38 ) 39 ) 40 } 41 }