Get CGRect of View

Update: improved and simplified a possible solution to read rect of any view in any coordinate space via helper extension. Works since Xcode 11.1, retested with Xcode 13.3.

Main part:

func rectReader(_ binding: Binding<CGRect>, _ space: CoordinateSpace = .global) -> some View {
    GeometryReader { (geometry) -> Color in
        let rect = geometry.frame(in: space)
        DispatchQueue.main.async {
            binding.wrappedValue = rect
        }
        return .clear
    }
}

Usage the same

Text("Test").background(rectReader($rect))

or with new extension

Text("Test").reading(rect: $rect)

Complete findings and code is here

Leave a Comment