I would like to stop GeometryReader
from interfering with my layout in a VStack
but I'm not sure what the correct approach is.
Given the example of a simple graph with a title and caption:
struct Graph: View {
var body: some View {
HStack(spacing: 0) {
Color.red.frame(width: 100, height: 80)
Color.blue.frame(width: 100, height: 120)
Color.green.frame(width: 100, height: 180)
}
}
}
struct GraphExample: View {
var body: some View {
VStack {
Text("My graph")
// Graph represents a custom view with a natural and non-static height
Graph()
Text("My graph caption")
}
}
}
Produces this expected result:
But if we update the Graph
view to use a GeometryReader
to evenly split the graph across the width of the screen the layout changes.
struct Graph: View {
var body: some View {
GeometryReader { proxy in
HStack(spacing: 0) {
Color.red.frame(width: proxy.size.width / 3, height: 80)
Color.blue.frame(width: proxy.size.width / 3, height: 120)
Color.green.frame(width: proxy.size.width / 3, height: 180)
}
}
}
}
This makes the Graph
view fill all available space in VStack
Is there a way to allow Graph
view to just fill its natural height up, and not consume all available height while still using the GeometryReader
.
Bear in mind that Graph
could be any view here where the exact size is not known, so setting a static size is not possible. i.e. without GeometryReader
, Graph
can takes up only the needed amount of vertical space in the VStack.