Skip to content

Instantly share code, notes, and snippets.

@laevandus
Created September 4, 2022 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laevandus/cd53c17945d2d6141323a2b93e7cf82d to your computer and use it in GitHub Desktop.
Save laevandus/cd53c17945d2d6141323a2b93e7cf82d to your computer and use it in GitHub Desktop.
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