Implement Geometry Reader SwiftUI

Farras Doko
2 min readFeb 17, 2021
measuring View using GeometryReader
Photo by Wander Fleur on Unsplash

Hello this is my first Medium story, I am sorry if my word isn’t structured. So I want to share with you how to measure a View using GeometryReader. I have a problem on it before as SwiftUI is very different from UIKit auto-layout. It will be documentation for me too 😉.

There is certain conditions we need to measure our view, such as calculating when the view reach the maximum width plus button will be disabled or when scrollView reach some height scrolling is enabled.

This is when GeometryReader is used. GeometryReader tells us size & coordinate space of its container view. This is useful on a certain conditions.

Let's go ahead and take a look at the demonstration of implementing it.

Lets Get Started

Here I will use PreferenceKey to pass the data to the View Hierarchy. PreferenceKey using key and value to pass the data and observe it.

We need to declare a struct conform to the PreferenceKey protocol and add two stubs from the protocol. They are: default value and reduce method.

struct SizeKey: PreferenceKey {   static var defaultValue: CGSize = .zero
static func reduce(value:inout CGSize, nextValue: () -> CGSize) {
value = nextValue()
}
}

Create function to the View extension to make it reusable.

extension View {  func measureSize(_ size: @escaping (CGSize)->()) -> some View {   background(     GeometryReader(content: { geometry in
self
.preference(key: SizeKey.self, value: geometry.size)
})
.onPreferenceChange(SizeKey.self, perform: size)
) }}

Now call the function on your view

struct ContentView: View {  var body: some View {   Text("Hiya Hiya Hiya")
.measureSize {
print(print("size: \($0)"))
}
}
}

--

--