Skip to content

Instantly share code, notes, and snippets.

@laevandus
Created September 4, 2022 10:35
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
struct PrepareViewData: ViewModifier {
@State var hasPrepared = false
let action: (() -> Void)
func body(content: Content) -> some View {
content
.onAppear {
if !hasPrepared {
action()
hasPrepared = true
}
}
}
}
extension View {
func prepare(perform action: @escaping () -> Void) -> some View {
modifier(PrepareViewData(action: action))
}
}
struct ContentView: View {
@StateObject var viewModel = ViewModel()
var body: some View {
VStack {
// redacted
}
.prepare {
viewModel.prepare()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment