I'm trying to achieve the following layout with SwiftUI in iOS 14:
I have an inner ScrollView
with a couple of "cells" each of which has the same aspect ratio. This inner ScrollView
scrolls its content horizontally and is part of a view tree that is nested within an outer ScrollView
which scrolls vertically.
Now I want to size the cells in a fashion that I can fit 4 of them in a (visible) row.
The width of the inner ScrollView is determined by the upper view tree (i.e. it's set from outside), but it's not fixed (for example, its frame might have a maxWidth
of 500 which would result in a width of 500 on an iPad, but a smaller width on an iPhone, depending on the screen size). So I cannot simply do some maths by passing the width minus some padding into the child view or something like that.
So in code, my question ist the following:
struct MyView: View {
var body: some View {
ScrollView(.vertical) {
ScrollView(.horizontal) {
HStack(spacing: 8) {
ForEach(1..<8) { index in
RoundedRectangle(cornerRadius: 8)
.fill(.blue)
.aspectRatio(1, contentMode: .fit)
.frame(width: availableWidth / 4) // ← Here ❓
}
}
}
.frame(maxWidth: 500)
.padding()
}
}
}
How do I get the availableWidth
here (i.e. the width proposed to the HStack
) so that I can size the "cells" (RoundedRectangle
s) as desired?
It seems like the only way to go is with GeometryReader
, but if I use a geometry reader within a scroll view, it will cause the scroll view to expand unnecessarily because GeometryReader
always returns the proposed size as its ideal size.