UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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()
            }
        //}
    }
}

1      

@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.

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.