I'm making a simple View in SwiftUI, a box with a line running through it. Here is the (working) code:
struct DrawLine: View {
let boxSize = CGFloat(300.0)
var body: some View {
ZStack {
Rectangle()
.stroke(lineWidth: 2.0)
.fill(Color.purple)
.frame(width: self.boxSize, height: self.boxSize, alignment: .center)## Heading ##
GeometryReader { geometry in
Path { path in
path.move(to: CGPoint(x: 1, y: 1))
path.addLine(to: CGPoint(x: geometry.size.width - 1, y: geometry.size.height - 1))
}
.stroke(lineWidth: 2)
.fill(Color.orange)
}
}
.frame(width: 50, height: 50).border(Color.black)
}
}
This works great, as shown here:
But if I take out the bit that defines the ZStack with a frame (.frame(width: 50, height: 50)
), the line takes up the entire screen as shown below. Why is that?
GeometryReader always grows as much as possible. If not limited by anything (i.e., your ZStack frame()), then it occupies the whole screen. That is the intended behavior. GeometryReader is trying to give as much as possible to its descendant.
GeometryReader expands both horizontally and vertically, as Spacer does in VStack and HStack.
If you do not restrict the size of the ZStack, the ZStack will grow with the GeometryReader. The same way a HStack or VStack grow with a Spacer inside them.