yuraist
yuraist

Reputation: 131

How to get frames (size and coordinates) for different views in SwiftUI?

I need to get frames for multiple views inside a VStack. I think using the GeometryReader but it returns the necessary parameters only for the parent. How can I get these parameters for each view on the screenshot below?

Layout I need to get frames for

Upvotes: 2

Views: 2506

Answers (1)

yuraist
yuraist

Reputation: 131

We can use the GeometryReader inside the overlay on needed views and store necessary frames in an array or as separate variables.

ForEach(0..<n) { number in
  YourView()
    .overlay(
      GeometryReader { geometry in
        Color.clear
          .onAppear {
            self.buttonFrames[number] = geometry.frame(in: .global)
          }
        }
    )
}

For more details, you can check this source: https://github.com/twostraws/SwiftOnSundays/blob/master/020%20Switcharoo/Project/Switcharoo/ContentView.swift and the full tutorial: https://www.youtube.com/watch?v=ffV_fYcFoX0

Upvotes: 2

Related Questions