1

I am trying to use a scroll view for scrollable content, but whenever I nest my views inside the Scroll View, I have noticed that the views from my stacks vanish back into the view hierarchy and nothing remains visible on the screen. I have also seen that whenever I am using a ScrollView, it adds another Hosting View Controller and I don't know if this is the normal behaviour.

    var body: some View {
    NavigationView {
        ScrollView(.vertical, showsIndicators: false) {
            VStack {
                ForEach(bookLibrary.indices, id: \.self) { index in
                    HStack {
                        ForEach(self.bookLibrary[index], id: \.self) { book in
                            BookView(book: book)
                        }
                    }
                }
            }
        }
    }
}

Getting this view hierarchy. You can also see that the HostingScrollView has a width of 0.

enter image description here

AndreiVataselu
  • 216
  • 2
  • 16

2 Answers2

1

If you don't want to use GeometryReader just insert zero height view with correct width like this

var body: some View {
    ScrollView {
        VStack {
            Color.clear
                .frame(maxWidth: .infinity, maxHeight: 0)
            ForEach(...) { each in
                ...
            }
        }
    }
}
Petr Syrov
  • 14,689
  • 3
  • 20
  • 30
0

While not a perfect solution, you can use GeometryReader to set the scroll view's frame to the same width as its superview.

NavigationView {

    GeometryReader {geometry in

        ScrollView(.vertical) {

            // TODO: Add content

        }
        .frame(width: geometry.size.width)

    }

}

This workaround was inspired by Rob Mayoff's answer on another question.

Barnyard
  • 273
  • 3
  • 11