ktyd
ktyd

Reputation: 53

Why won't a nested scrollview respond to scrolls in swiftUI?

I'm building an SwiftUI app with a dropdown menu with a vertical ScrollView within another vertical ScrollView. However, the dropdown menu one (the nested one) won't scroll. I would like to give it priority somehow. It seems like a simple problem, but I have scoured the internet but cannot find an adequate solution. Here is the basic code for the problem (the code is cleaner in the app but copy and pasting particular snippets did not work very well):

    ScrollView{
    VStack{
        (other stuff)
        DropdownSelector()
        (other stuff)
}
}

struct DropdownSelector(){
ScrollView{
VStack(alignment: .leading, spacing: 0) {
            ForEach(self.options, id: \.self) { option in
                (do things with the option)
            }
}
}

Upvotes: 4

Views: 9077

Answers (1)

George
George

Reputation: 30391

Creating nested ScrollViews in the first place is probably a bad idea. Nonetheless, there is a solution.

Because with ScrollView it scrolls as much as the content height, this is a problem when they are nested. This is because the inner ScrollView isn't limited in height (because the outer ScrollView height just changes), so it acts as if it wasn't there at all.

Here is a minimal example demonstrating the problem, just for comparison:

struct ContentView: View {
    var body: some View {
        ScrollView {
            VStack {
                Text("Top view")

                DropdownSelector()

                Text("Bottom view")
            }
        }
    }
}

struct DropdownSelector: View {
    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 0) {
                ForEach(0 ..< 10) { i in
                    Text("Item: \(i)")
                }
            }
        }
    }
}

To fix it, limit the height of the inner scroll view. Add this after DropdownSelector():

.frame(height: 100)

Result

Upvotes: 10

Related Questions