Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swipe between two pages with Segmented-style Picker in SwiftUI

I have a Picker with .pickerStyle(SegmentedPickerStyle()) to make it a segmented control. I want to make the pages smoothly swipe between, rather than replacing the view using a conditional statement.

Here is a gif of what I have made so far:

What I have made

Here is the code so far (controlled by an if, instead of switching between different pages):

struct AuthView: View {

    @State private var authPath = 0

    /* ... */

    var body: some View {
        VStack {
            Picker(selection: $authPath, label: Text("Authentication Path")) {
                Text("Log In").tag(0)
                Text("Sign Up").tag(1)
            }
            .pickerStyle(SegmentedPickerStyle())

            Spacer()

            if authPath == 0 {
                LogInView(/* ... */)
            } else {
                SignUpView(/* ... */)
            }

            Spacer()
        }
        .padding()
        .background(Color("Color.Background").edgesIgnoringSafeArea(.all))
    }
}

I want something similar to UIPageViewController. If there is a SwiftUI version or a good alternative, that would really help.

However, if I do need to resort to UIKit with UIViewRepresentable, I don't know how I would implement it with SwiftUI.

like image 691
George Avatar asked Oct 18 '25 21:10

George


1 Answers

I managed to achieve this by creating both Picker and TabView like this:

struct ContentView: View {
    @State private var selectedPage: Int = 0

    var body: some View {
        VStack {
            Picker("", selection: $selectedPage) {
                Text("First").tag(0)
                Text("Second").tag(1)
                Text("Third").tag(2)
            }.pickerStyle(.segmented)
                
            TabView(selection: $selectedPage) {
                FirstView().tag(0)
                    
                SecondView().tag(1)
                    
                ThirdView().tag(2)
            }.tabViewStyle(.page)
        }
    }
}

Both of the Picker and TabView share the same selection state so when the Picker get selected or the TabView get scrolled, the other changed as well.

like image 196
cleanrun Avatar answered Oct 20 '25 11:10

cleanrun