Skip to content

Instantly share code, notes, and snippets.

@cedric-elca
Created November 22, 2019 10:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cedric-elca/d1ebf92ef8ff8c62039e8537125a7b48 to your computer and use it in GitHub Desktop.
Save cedric-elca/d1ebf92ef8ff8c62039e8537125a7b48 to your computer and use it in GitHub Desktop.
import SwiftUI
struct ContentView: View {
@State private var show = false
var body: some View {
NavigationView {
List(["1", "2", "3", "4", "5"], id: \.self) { row in
Text(row)
}
.navigationBarTitle(Text("With NavigationView"))
.navigationBarItems(trailing: Button(action: {
self.show.toggle()
}) {
Text("Show")
})
}
// VStack {
// Text("Without NavigationView")
// Button(action: {
// self.show.toggle()
// }) {
// Text("Show")
// }
// Spacer()
// }
.toast(show: $show, text: "Test")
}
}
struct ToastView<Content>: View where Content: View {
@Binding var show: Bool
let text: String
var overlaidContent: () -> Content
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .bottom) {
self.overlaidContent()
if self.show {
VStack {
Text(self.text)
.multilineTextAlignment(.center)
.padding()
}
.frame(width: geometry.size.width < geometry.size.height ? geometry.size.width * 0.85 : geometry.size.width * 0.65)
.background(Color(UIColor.secondarySystemBackground))
.cornerRadius(20)
.padding([.vertical], 15)
.animation(.easeInOut(duration: 1.0))
.transition(.move(edge: .bottom))
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.show.toggle()
}
}
}
}
}
}
}
extension View {
func toast(show: Binding<Bool>, text: String) -> some View {
ToastView(show: show, text: text) {
self
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment