Last active
September 24, 2019 12:51
-
-
Save plivesey/2cffe8bf4203e7d6d2632e386eaa36db to your computer and use it in GitHub Desktop.
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 ContentView: View { | |
@ObservedObject var toastManager = ToastManager() | |
@State var offset: CGFloat = 60 | |
init() { | |
// This actually throws an error: Escaping closure captures mutating 'self' parameter | |
toastManager.onShow = { self.onShow() } | |
} | |
var body: some View { | |
ZStack(alignment: .bottom) { | |
ChildView().environmentObject(toastManager) | |
if toastManager.show { | |
Text(toastManager.text).offset(x: 0, y: offset).onTapGesture { | |
self.hide() | |
} | |
} | |
} | |
} | |
func onShow() { | |
withAnimation { | |
self.offset = 0 | |
} | |
} | |
func hide() { | |
withAnimation { | |
self.offset = 60 | |
} | |
} | |
} | |
struct ChildView: View { | |
@EnvironmentObject var toastManager: ToastManager | |
var body: some View { | |
VStack { | |
Spacer() | |
Button(action: { self.toastManager.show(text: "Test toast") }) { | |
Text("Show toast") | |
} | |
Spacer() | |
} | |
} | |
} | |
class ToastManager: ObservableObject { | |
var onShow: () -> Void = {} | |
@Published var text = "" | |
@Published var show = false | |
func dismiss() { | |
show = false | |
} | |
func show(text: String) { | |
self.text = text | |
show = true | |
onShow() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment