BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: How to get ScrollView, Picker, and TabView to play nice?

Forums > SwiftUI

I'm attempting to embed a Picker in a larger ScrollView that controls the content immediately below the Picker - essentially I'd like the picker to control a portion of the larger ScrollView.

The below test code mostly does that if ScrollView is commented out...obviously not ideal. Once I bring the ScrollView back to life, the TabView content vanishes. I did make it all work by encompassing the ScrollView in a geometry reader and then set the frame height to the content height, but that wasn't ideal as it seemed to add a lot of extra space unnecessarily.

I suspect there's a better way to implement this that I'm missing - maybe TabView isn't the solution? You could also use if/else statements that show views based on tabSelectedValue, with animations added to make it transition smoothly.

struct TestView: View {
    @State private var tabSelectedValue = 0

    var body: some View {
        //ScrollView {
            VStack {
                // Picker
                Picker("", selection: $tabSelectedValue) {
                    Text("First").tag(0)
                    Text("Second").tag(1)
                }
                .pickerStyle(SegmentedPickerStyle())
                .padding()

                // TabView
                TabView(selection: $tabSelectedValue) {
                    Text("Content for first tab")
                        .tag(0)
                    Text("Content for second tab")
                        .tag(1)
                }
                Spacer()
            }
        //}
    }
}

   

@aarku  

A number of SwiftUI built in views, including TabView, really are only meant (sadly) for their exact intended purpose: tab navigation at the bottom of the screen that looks and behaves standardly. They are not at all flexible, besides a "paging" control type look which has its own problems.

Just use a switch statement on tabSelectedValue to pick what content you want to show. If you want animation, use .animation(.easeInOut, value: tabSelectedValue) or similar on a view that contains the switch statement.

   

Save 50% in my Black Friday sale.

SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.