4

I have a swiftui project. I am using pageview. Normally, when it comes to the last page, it does not scroll further because the pages are finished. What I want is this: the pages continue after reaching the last page. Let's start again from the first page. so I want my page order to be like this:

page 1 -> page 2 -> page 3 -> page 1 -> page 2 -> page 3 -> page 1 .....

I want it to repeat itself like this all the time.

struct PageControllerView: View {
    var body: some View {
        TabView {
            Text("page 1")
            Text("page 2")
            Text("page 3")
        }
        .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
    }
}
ursan526
  • 485
  • 3
  • 10

1 Answers1

0

Well you need to use the TabView with a selection:

struct PageControllerView: View {
    @State var selection = 1
    var body: some View {
        TabView(selection: $selection) {
            Text("page 3").tag(0) //same as last view for swipe effect
            Text("page 1").tag(1)
            Text("page 2").tag(2)
            Text("page 3").tag(3)
            Text("page 1").tag(4) //same as first view for swipe effect
            
        }//.tabViewStyle(PageTabViewStyle()) BTW, You don't need that
        .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
        .onChange(of: selection) { newValue in
            if selection == 4 { //last tag + 1
                selection = 1 //first tag
            }else if selection == 0 { //first tag - 1
                selection = 3 //last tag
            }
        }
    }
}

This also works with ForEach, but don't forget to choose a suitable tag.

Timmy
  • 4,098
  • 2
  • 14
  • 34
  • Good try, but put full screen visible view, eg. color, on pages and you see that on swipe it behaves bad - half of empty "stub" page and then jump to next... but it would be great if it would work. – Asperi Jul 18 '22 at 19:03
  • Ah yes, I see it now… – Timmy Jul 18 '22 at 19:06
  • if it will have solution i can use it in foreach. Since there will be pictures on the pages, the user should not notice. – ursan526 Jul 18 '22 at 19:35