Skip to content

Instantly share code, notes, and snippets.

@seifscape
Forked from mattyoung/OnFirstAppear.swift
Created November 29, 2023 17:44
Show Gist options
  • Select an option

  • Save seifscape/b7aa0ad3e3b43dfec6f96e737f8998ee to your computer and use it in GitHub Desktop.

Select an option

Save seifscape/b7aa0ad3e3b43dfec6f96e737f8998ee 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