Skip to content

Instantly share code, notes, and snippets.

@StewartLynch
Created June 29, 2024 19:28
Show Gist options
  • Save StewartLynch/36d0fa797f47704d97bf9fbf3e49be92 to your computer and use it in GitHub Desktop.
Save StewartLynch/36d0fa797f47704d97bf9fbf3e49be92 to your computer and use it in GitHub Desktop.
firstOnAppear View Modifier
struct FirstOnAppearModifier: ViewModifier {
@State private var hasPerformedAction = false
let action: (() -> Void)?
func body(content: Content) -> some View {
content
.onAppear {
if !hasPerformedAction {
hasPerformedAction = true
action?()
}
}
}
}
extension View {
/// Same as `onAppear(perform:)` except the optional `action` only triggers the _first_ time the view appears, instead of _every_tiime.
func firstOnAppear(performOnce action: (() -> Void)? = nil) -> some View {
modifier(FirstOnAppearModifier(action: action))
}
}
/*
// Example Usages
struct View1: View {
var body: some View {
Text("View 1")
.firstOnAppear {
print("View 1 appears")
}
}
}
struct View2: View {
var body: some View {
Text("View 2!")
.onAppear {
print("View 2 appears")
}
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment