SwiftUI : ViewDidLoad & ViewDidAppear
Coming from the UIKit world — there have been multiple callbacks for view lifecycle, when view used to start loading
- viewDidLoad
- viewWillAppear
- viewDidAppear
In SwiftUI — the most closest available callback is onAppear only — which gets called everytime when view is loaded in hierarchy — equivalent to viewDidAppear of UIKit
There comes several use-cases when we need to perform few actions only once while few actions everytime. For this particular requirement — We have a solution -
I have written a viewModifier — which can be appended to any View -
extension View {
func onViewRenderCycle(didLoadAction: @escaping () -> Void,
didAppearAction: (() -> Void)? = nil) -> some View {
modifier(ViewLifeCycleModifier(didLoadAction: didLoadAction,
didAppearAction: didAppearAction))
}
}
struct ViewLifeCycleModifier: ViewModifier {
let didLoadAction: () -> Void
let didAppearAction: (() -> Void)?
@State
private var appeared = false
func body(content: Content) -> some View {
content.onAppear {
if !appeared {
appeared = true
didLoadAction()
} else {
didAppearAction?()
}
}
}
}
On your View Structs — simply append onViewRenderCycle method to receive different callbacks for first time & subsequent view render cycles
struct MainView : View {
var body: some View {
VStack{
Text("Hello World")
}
.onViewRenderCycle {
// ViewDidLoad - FirstTime
} didAppearAction: {
// ViewDidAppear - Subsequent Times
}
}
}