Nat
Nat

Reputation: 1792

Is there a .onReappear equivalent in SwiftUI

I have this view that has a simple VStack that contains 4 IF conditions, each condition will show the right view:

VStack{
        if(showLogin){
            LoginView()
        }
        if(showMain){
            Main()
        }
        if(showSplash){
            Text("Splash screen")
        }
        if(showNoInternet){
            noInternetView(showNoInternet: $showNoInternet, showSplash: $showSplash)
        }
    }

For this view I have a .onAppear() to run code when this view appears:

@State var showLogin = false
@State var showMain = false
@State var showNoInternet = false
@State var showSplash = true

var body: some View {

VStack{
        if(showLogin){
            LoginView()
        }
        if(showMain){
            Main()
        }
        if(showSplash){
            Text("Splash screen")
        }
        if(showNoInternet){
            noInternetView(showNoInternet: $showNoInternet, showSplash: $showSplash)
        }
    }
    .onAppear(){ ... }
}

Within the code of .onAppear() I check if the user has internet connection, if they don't then I toggle both the splash and the showNoInternetView to hide the splash screen and show the No Internet connection message. When the user presses a button in the showNoInternetView, it does the opposite to hide the message and show the splash screen again, which I would like to run the same code again within the .onAppear(). Obviously I know to re-render a view you'd have to change a state - which is what I do to update the views.

How would I invoke the .onAppear() function again each time I go back to the original splash view (as if it's the first time the view is being run)?

Upvotes: 1

Views: 149

Answers (1)

Asperi
Asperi

Reputation: 258345

Attach it instead to splash view directly, so once you come into condition of splash view it will run as expected.

    if(showSplash){
        Text("Splash screen")
           .onAppear(){ ... }        // << move here !!
    }

Upvotes: 1

Related Questions