简体   繁体   中英

How to change PageTabView programmatically in iOS 14, SwiftUI 2?

I'm exploring new things came in Xcode 12 and SwiftUI 2.0

I have created a pageview onboarding screen with TabView and PageTabViewStyle in Xcode 12, iOS 14, Swift UI 2. I want to add the next button when clicking on it, the page should move to the second view. Here Text("Hello") .

struct OnBoardingView: View {
    var body: some View {
        TabView {
            Text("Hi")
            Text("Hello")
            Text("Welcome")
        }
        .tabViewStyle(PageTabViewStyle())
        .indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))
    }
}

Here is a demo of solution. Tested with Xcode 12 / iOS 14

演示

struct OnBoardingView: View {
    @State private var selectedPage = 0
    var body: some View {
        VStack {
            HStack {
                Button("<") { if selectedPage > 0 {
                    withAnimation { selectedPage -= 1 }
                } }
                Spacer().frame(width: 40)
                Button(">") { if selectedPage < 2 {
                    withAnimation { selectedPage += 1 }
                } }
            }
            TabView(selection: $selectedPage) {
                Text("Hi").tag(0)
                Text("Hello").tag(1)
                Text("Welcome").tag(2)
            }
            .tabViewStyle(PageTabViewStyle())
            .indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM