SwiftUI - frameReader

Updated
Aug 2, 2022 5:47 AM
Created
Aug 2, 2022 5:46 AM
Tags
Attributes
public extension View {
    /// Read a view's frame. From https://stackoverflow.com/a/66822461/14351818
    func frameReader(in coordinateSpace: CoordinateSpace = .global, rect: @escaping (CGRect) -> Void) -> some View {
        return background(
            GeometryReader { geometry in
                Color.clear
                    .preference(key: ContentFrameReaderPreferenceKey.self, value: geometry.frame(in: coordinateSpace))
                    .onPreferenceChange(ContentFrameReaderPreferenceKey.self) { newValue in
                        DispatchQueue.main.async {
                            rect(newValue)
                        }
                    }
            }
            .hidden()
        )
    }