I'm trying to dynamically size some views which end up being placed inside of a scrollview. Here is the simplest sample code I can think of:
struct RootView: View {
var body: some View {
ScrollView {
VStack(alignment: .leading) {
// More views above
HStack(spacing: 16) {
MyView()
MyView()
}
.padding([.leading, .trailing], 16)
// More views below
}
}
}
}
struct MyView: View {
var body: some View {
VStack(alignment: .leading, spacing: 24) {
Image("myImage")
.resizable()
.scaledToFill()
VStack(alignment: .leading, spacing: 0) {
Text("Text")
OtherView()
}
}
}
}
I think really the main issue I'm having is regarding how to dynamically size each MyView inside of the HStack.
If I wanted the Image in MyView to be sized to fill its width and grow vertically to maintain its aspect ratio, and then also size each MyView in RootView to be 40% of RootView's width, what is the best way to accomplish this?
I've tried using GeometryReader but when it's nested inside the ScrollView, it causes the view its used in to collapse in on itself. If I use it outside of the ScrollView, I'm effectively always going to be getting the screen width (in this application) which isn't always what I need. On top of that, imagine that MyView is nested deeper in the view hierarchy and not called directly from RootView, but rather one of its child views. Or better yet, imagine that we don't know that RootView doesn't know its rendering a MyView if the view is determined at runtime.
To give a little context to anyone who is interested in some backstory, the app I'm trying to build is very modular in nature. The idea is that we really only have one "container view" struct that determines which views to render at runtime. We basically have a ScrollView in this container view and then any number of subviews. I'm really struggling with why it seems so difficult to set a view's content dimensions relative to its parent.