Skip to content

Instantly share code, notes, and snippets.

@GeorgeElsham
Last active January 28, 2024 13:51
Show Gist options
  • Save GeorgeElsham/1f3f0eef3bd986a1d3d1a6715e52e9ba to your computer and use it in GitHub Desktop.
Save GeorgeElsham/1f3f0eef3bd986a1d3d1a6715e52e9ba to your computer and use it in GitHub Desktop.
Get geometry of view without breaking the layout
/*
MIT License
Copyright (c) [2023] [George Elsham]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import SwiftUI
extension View {
/// Read the geometry of the current view. Save the returned value in
/// a `@State` variable, to be used anywhere within the view.
///
/// - Parameter geometry: Geometry closure containing this view's geometry.
/// - Returns: Modified view.
func geometryReader(_ geometry: @escaping (GeometryProxy?) -> Void) -> some View {
modifier(GeometryReaderModifier(geometry: geometry))
}
}
fileprivate struct GeometryReaderModifier: ViewModifier {
private struct GeometryPreferenceKey: PreferenceKey {
static func reduce(value: inout GeometryProxy?, nextValue: () -> GeometryProxy?) {
value = nextValue()
}
}
private let geometry: (GeometryProxy?) -> Void
init(geometry: @escaping (GeometryProxy?) -> Void) {
self.geometry = geometry
}
func body(content: Content) -> some View {
content
.background(
GeometryReader { geo in
Color.clear
.preference(key: GeometryPreferenceKey.self, value: geo)
}
)
.onPreferenceChange(GeometryPreferenceKey.self) { geo in
geometry(geo)
}
}
}
extension GeometryProxy: Equatable {
public static func == (lhs: GeometryProxy, rhs: GeometryProxy) -> Bool {
lhs.frame(in: .global) == rhs.frame(in: .global)
}
}
@abhillman
Copy link

Would you be comfortable adding a license?

@GeorgeElsham
Copy link
Author

@abhillman Added an MIT license—I don't care what is done with this code, but if you think a different license would fit better, I'm happy to modify it. Hope this helps :)

@Pikuseru
Copy link

Would you be able to provide an example of how to use this, I'm attempting to use it in a playground to get the size and then store it in a @State var, but Swift UI seems to get into an infinite loop:

struct MeasuredView: View {
    @State var size: CGSize?

    var body: some View {
        VStack {
            if let size {
                Text("Size is \(size.width) \(size.height)")
            } else {
                Text("Size is unknown")
            }
        }.geometryReader { proxy in
            size = proxy?.size
        }
    }
}

@GeorgeElsham
Copy link
Author

@Pikuseru You’re effectively getting the size of a Text which keeps changing every time you read a new size, hence the infinite loop. You should measure something that doesn’t create a cycle—such as the Text("Size is unknown") view.

Additionally, make the VStack size dependent on some other content and add the Texts as an overlay.

@Pikuseru
Copy link

@GeorgeElsham thank you 🙂👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment