1

My problem is that TabView is not updating.

I want to log-in and then re-render another view (Profile Screen) instead of (Login Screen) in the same TabItem.

The TabView goes to ProfileScreen only after i kill the app and reopen it.

Here's the TabView code:

import SwiftUI

struct ContentView: View {
    
    @State var userToken: String = UserDefaults.standard.string(forKey: "UserToken") ?? ""
    var body: some View {
        TabView{
            HomeScreen(text: .constant("")).tabItem({ Image(systemName: "house") }).tag(0)
            Text("Cart").tabItem({ Image(systemName: "cart") }).tag(1)
            if userToken.isEmpty {
                LoginScreen().tabItem({ Image(systemName: "person") }).tag(2)
            } 
            else { 
                ProfileScreen().tabItem({ Image(systemName: "person") }).tag(2)
            }
        }
    }
    
}

Things I have tried:

  • Passing different @State values to both screens
  • Rendering Profile Screen in LoginScreen but it renders on top of the TabView
regina_fallangi
  • 2,080
  • 2
  • 18
  • 38

2 Answers2

2

If you're using the latest SwiftUI, consider using @AppStorage instead of @State:

@AppStorage("UserToken") var userToken: String = ""
Danny B
  • 93
  • 5
0

If you are modifying the value of userToken in any other view, for example may be LoginView, you need a mechanism to inform the content view about that update.

You can consider using LocalNotifications here for sending the update to ContentView so that the view reloads on status update.

Anjali Aggarwal
  • 611
  • 4
  • 8