GeometryReader in SwiftUI

DevTechie
DevTechie
Published in
7 min readFeb 6, 2022

--

Photo by Federico Beccari on Unsplash

By the end of this article, you would not only know how to use GeometryReader but would have also built stretchy header, purely using SwiftUI and GeometryReader. Here is what we will build:

Building layout is easy and fun in SwiftUI and most of the time we are good with Stack based layout but there are cases where we need more control over the layout on the screen for example, we may need to draw a rectangle on the screen that’s half the size of main screen(parent view).

Let’s draw that rectangle.

struct GeometryReaderExample: View {
var body: some View {
GeometryReader {geoProxy in
Rectangle()
.fill(Color.orange.opacity(0.5))
.frame(width: geoProxy.size.width / 2, height: geoProxy.size.height / 2)
.position(x: geoProxy.size.width / 2, y: geoProxy.size.height / 2)
}
}
}

GeometryReader provides its size information via GeometryProxy struct in the closure. Notice the use of geoProxy in code above 👆to query size of the GeometryReader’s bounding box.

--

--

DevTechie
DevTechie

Published in DevTechie

DevTechie.com is all about sharing knowledge by practical means. We focus on solving real world challenges via code.