Skip to content

Instantly share code, notes, and snippets.

@mattyoung
Created April 9, 2021 19:37
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mattyoung/0deb368e64fe8e06a42412ecedc34604 to your computer and use it in GitHub Desktop.
Save mattyoung/0deb368e64fe8e06a42412ecedc34604 to your computer and use it in GitHub Desktop.
import SwiftUI
private struct OnFirstAppear: ViewModifier {
let perform: () -> Void
@State private var firstTime = true
func body(content: Content) -> some View {
content.onAppear {
if firstTime {
firstTime = false
perform()
}
}
}
}
extension View {
func onFirstAppear(perform: @escaping () -> Void) -> some View {
modifier(OnFirstAppear(perform: perform))
}
}
struct Child: View {
var body: some View {
Color.red
.onFirstAppear {
print("Child.onFirstAppear()")
}
.navigationTitle("Child")
}
}
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink("Child", destination: Child())
.navigationTitle(Text("Parent"))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment