Created
April 2, 2020 11:44
-
-
Save KanshuYokoo/3b0e0f01dae3de81544e6b39db4ca58a to your computer and use it in GitHub Desktop.
SwiftuI ToastView example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ToastView: View { | |
@State private var liked: Bool = false | |
var body: some View { | |
VStack { | |
LikeButton(liked: $liked) | |
} | |
.toast(isShowing: $liked, text: Text("Hello toast!")) | |
} | |
} | |
//https://stackoverflow.com/questions/56550135/swiftui-global-overlay-that-can-be-triggered-from-any-view | |
struct Toast<Presenting>: View where Presenting:View { | |
@Binding var isShowing: Bool | |
let presenting: () -> Presenting | |
let text: Text | |
var body: some View { | |
GeometryReader { geometry in | |
ZStack(alignment: .center) { | |
self.presenting() | |
.blur(radius: self.isShowing ? 1 : 0) | |
VStack { | |
self.text | |
} | |
.frame(width: geometry.size.width / 2, | |
height: geometry.size.height / 5) | |
.background(Color.secondary.colorInvert()) | |
.foregroundColor(Color.primary) | |
.cornerRadius(20) | |
.transition(.slide) | |
.opacity(self.isShowing ? 1 : 0) | |
.onAppear { | |
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { | |
withAnimation { | |
self.isShowing = false | |
} | |
} | |
} | |
.onTapGesture(count: 1, perform: { | |
withAnimation { | |
self.isShowing = false | |
} | |
}) | |
} | |
} | |
} | |
} | |
struct LikeButton : View { | |
@Binding var liked: Bool | |
var body: some View { | |
Button(action: { self.toggleLiked() }) { | |
Image(systemName: liked ? "heart" : "heart.fill") | |
} | |
} | |
private func toggleLiked() { | |
self.liked = !self.liked | |
// NEED SOME SORT OF TOAST CALLBACK HERE | |
} | |
} | |
extension View { | |
func toast(isShowing: Binding<Bool>, text: Text) -> some View { | |
Toast(isShowing: isShowing, | |
presenting: { self }, | |
text: text) | |
} | |
} | |
struct ToastView_Previews: PreviewProvider { | |
static var previews: some View { | |
ToastView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment