— SwiftUI, View Lifecycle, onAppear — 1 min read
In SwiftUI, the onAppear
modifier is commonly used to perform actions when a view appears on screen. It's useful for tasks like loading data, initializing variables, or updating the UI. By default, the onAppear
modifier triggers the associated code block every time the view becomes visible. However, there are scenarios where you may want certain code to execute only once, such as fetching initial data from a server or performing one-time setup. In this article, we will explore techniques to achieve this behavior and ensure that the code inside the onAppear
modifier runs only once.
@State
FlagOne way to achieve one-time execution of code inside the onAppear
modifier is by using an @State
property to track whether the code has already been executed. Let's look at an example:
1struct ContentView: View {2 @State private var didFinishSetup = false3 4 var body: some View {5 VStack {6 Text("Welcome to my app!")7 }8 .onAppear {9 if !didFinishSetup {10 // Perform one-time setup here11 print("Performing one-time setup...")12 13 // Mark setup as finished14 didFinishSetup = true15 }16 }17 }18}
In this example, we introduce a boolean flag called didFinishSetup
using the @State
property wrapper. The first time the view appears, the code inside the onAppear
modifier will execute the one-time setup logic. Subsequent appearances of the view won't trigger the setup code because the flag is already set to true
.
Another approach to execute code only once in SwiftUI's onAppear
is by creating a custom view modifier. This allows you to encapsulate the behavior and reuse it across different views.
Here's an example of a custom view modifier that leverages the @State
flag technique we discussed earlier:
1struct OnceOnAppearModifier: ViewModifier {2 @State private var didAppear = false3 4 func body(content: Content) -> some View {5 content.onAppear {6 if !didAppear {7 // Perform one-time action here8 print("Performing one-time action...")9 10 // Mark action as finished11 didAppear = true12 }13 }14 }15}16
17extension View {18 func onceOnAppear() -> some View {19 self.modifier(OnceOnAppearModifier())20 }21}
With this custom view modifier, you can use the onceOnAppear
modifier on any view to ensure that its associated code block executes only once upon appearance:
1struct ContentView: View {2 var body: some View {3 VStack {4 Text("Welcome to my app!")5 }6 .onceOnAppear()7 }8}
Using this technique, the code inside the onceOnAppear
modifier will run only the first time the view appears on screen.
By utilizing either an @State
flag or a custom view modifier, you can control when code inside the onAppear
modifier executes. These techniques allow you to perform initialization tasks, fetch data, or set up your view just once in SwiftUI. Remember to choose the approach that best fits your specific use case.