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

2      

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

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.