title: SwiftUI: On tap gesture switches views
body: <p>I have the following simplified code in a project using XCode 13.2. The intended functionality is to have 2 tabs (<code>Tab1</code> and <code>Tab2</code>), and the user is able to tap the screen on <code>Tab2</code> to toggle the background from red to green.</p>
  <p>Instead, however, when <code>Tab2</code> is clicked, the screen displays tab 1, instead of <code>Tab2</code> with the changed color. I'm wondering why the app goes to <code>Tab1</code> when <code>Tab2</code> is tapped.</p>
  <p>There are no NavigationLinks or actions that make the user go to <code>Tab1</code>. My only thought is that maybe the app is rebuilding when <code>Tab2</code> is clicked, which is why it goes back to the first tab? If so, are there any good workarounds for this?</p>
  <p><strong>Note</strong>: the color still changes on <code>Tab2</code>, but not before the app switches to <code>Tab1</code>.</p>
  <pre><code>
  struct ContentView: View {
      
      var body: some View {
          TabView {
              Tab1()
                  .tabItem {
                      Text(&quot;Tab 1&quot;)
                  }
              Tab2()
                  .tabItem {
                      Text(&quot;Tab 2&quot;)
                  }
          }
      }
  }
  
  struct Tab1: View {
      var body: some View {
          Text(&quot;Tab 1&quot;)
      }
  }
  
  struct Tab2: View {
      @State var isRed: Bool = false
      
      var body: some View {
          if !isRed {
              Color.green
                  .onTapGesture {
                      isRed = true
                  }
          } else {
              Color.red
                  .onTapGesture {
                      isRed = false
                  }
          }
      }
  }
  </code></pre>