Created
June 29, 2024 19:28
-
-
Save StewartLynch/36d0fa797f47704d97bf9fbf3e49be92 to your computer and use it in GitHub Desktop.
firstOnAppear View Modifier
This file contains 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
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