Michael Long
Dec 19, 2023

--

Typically call this onAppearOnce and implement it using the onAppear modifier.

Especially since executing the callback during view body evaluation has the possibility of triggering SwiftUI warnings or issues when attempting to update state during evaluation.

This approach is not recommended.

Note following code using your modifier does NOT work.

struct ContentView: View {

@State var n = 0

var body: some View {

Text("Hello \(n)!")

.onViewDidLoad { n += 1 }

.padding()

}

}

Displays "Hello 0!"

--

--

Michael Long
Michael Long

Written by Michael Long

I write about Apple, Swift, and SwiftUI in particular, and technology in general. I'm also a Lead iOS Engineer at InRhythm, a modern digital consulting firm.

No responses yet