4

a weird problem here - either a bug or I'm missing something simple.

I'm creating a TabView {} with a PageTabViewStyle(). It works perfectly, please see below and note the dots at the bottom (the ones that indicate which page is selected - please ignore weird glitches, this is only due to the gif animation compression)

enter image description here

However, as soon as I add a bound variable to track what is selected the indicator dots no longer change (and the selected page is not tracked either).

enter image description here

Code for the working version:

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        TabView() {
       
            SomePage(text:"page 1")
            SomePage(text:"page 2")
            SomePage(text:"page 3")
          
            
        }.tabViewStyle(PageTabViewStyle())
        .background(Color.gray)

    }
}

Code where dots don't update:

import SwiftUI

struct ContentView: View {
    
    @State var selected = 0
    
    var body: some View {
        TabView(selection: $selected) {
       
            SomePage(text:"page 1")
            SomePage(text:"page 2")
            SomePage(text:"page 3")
          
            
        }.tabViewStyle(PageTabViewStyle())
        .background(Color.gray)

    }
}

No idea why it happens. Could anyone help? Thanks!

darekm
  • 285
  • 1
  • 12

1 Answers1

4

You just need to add a .tag() to each page, like this:

struct TabViewTest: View {
    
    @State var selected = 0

    var body: some View {
        TabView(selection: $selected) {
            Color.red.edgesIgnoringSafeArea(.all)
                .tag(0)
            
            Color.blue.edgesIgnoringSafeArea(.all)
                .tag(1)

            Color.orange.edgesIgnoringSafeArea(.all)
                .tag(2)
        }
        .tabViewStyle(PageTabViewStyle())
    }
}
nicksarno
  • 3,850
  • 1
  • 13
  • 33
  • Right!!! I thought it was tracking just the number of the page in order, but in fact it tracks via tag values. Neat, thanks! – darekm Jan 21 '21 at 13:25