36

Is there a way to get a View's frame after layout? I'd like to draw a line connecting two views after layout has positioned them:

enter image description here

It seems I need something like measure in React.

9
  • @Fogmeister I mean a line connecting the two views. I updated the question.
    – Taylor
    Jun 9, 2019 at 21:22
  • 1
    @Fogmeister picture added :)
    – Taylor
    Jun 9, 2019 at 21:25
  • 1
    @MatteoPacini sorry for being unclear initially.
    – Taylor
    Jun 9, 2019 at 21:37
  • 1
    @Fogmeister It's already created audulus.com :)
    – Taylor
    Jun 9, 2019 at 22:10
  • 2
    @Taylor Could you please add a snippet of how you've drawn a line between two views? The answer by Jake is really not that self-explanatory and is very short and I just cannot find anything that explains this well. Would be very appreciated.
    – Big_Chair
    Aug 15, 2021 at 14:30

4 Answers 4

27

Use a GeometryReader to get the frame of each view and use the frame to determine the points for a path between the two views.

struct ContentView : View {
    var body: some View {
        GeometryReader { geometry -> Text in
            let frame = geometry.frame(in: CoordinateSpace.local)
            return Text("\(frame.origin.x), \(frame.origin.y), \(frame.size.width), \(frame.size.height)")
        }
    }
}
9
  • You’re returning a frame as a string?
    – matt
    Jun 10, 2019 at 4:24
  • I'm returning a Text view (i.e. SwiftUI's version of UILabel) that displays the frame on the screen as an example.
    – Jake
    Jun 10, 2019 at 4:26
  • 26
    Does this approach actually work? How would you access the values you get from the GeometryReader, from outside the view? That is where you need it, right?
    – Gusutafu
    Jul 2, 2019 at 13:51
  • 1
    @Gusutafu state. Apr 25, 2021 at 19:43
  • 1
    When I use GeometryReader on a view the view becomes misplaced.
    – andrewz
    May 11, 2022 at 16:21
4

To export the "as rendered" view coordinates, I created a set of arrays for the x,y coordinates, and saved them in the Model object. However, I had to NOT encapsulate them in @Published var, instead kept them as just "var", otherwise you get into an infinite loop of updating the coordinates and then re-rendering the view.

Using Apple's 'landmark' tutorial, the Model object was modified as follows:

import SwiftUI
import Combine

final class UserData: ObservableObject {
  @Published var showFavoritesOnly = false
  @Published var landmarks = landmarkData
 var circleImageX = Array(repeating: 0.0, count:20)
 var circleImageY = Array(repeating: 0.0, count:20)

}

Then, write to those arrays each time the CircleImage.swift is rendered using the following code, again from the 'landmark.swift' tutorial, saving the frame midpoints.

import SwiftUI

struct CircleImage: View {
  @EnvironmentObject var userData: UserData
  var landmark: Landmark

  var landmarkIndex: Int {
    userData.landmarks.firstIndex(where: {$0.id == landmark.id})!
  }
  var body: some View {

    ZStack {
      landmark.image
        .clipShape(Circle())
        .overlay(Circle().stroke(Color.white, lineWidth: 4))
        .shadow(radius: 10)
      VStack {

        GeometryReader { geometry -> Text in
          let frame = geometry.frame(in: CoordinateSpace.global)
          self.userData.circleImageX[self.landmarkIndex] = Double(frame.midX)
          return
            Text("\(frame.midX)")
              .foregroundColor(.red)
              .bold()
              .font(.title)
        }
        .offset(x: 0.0, y: 50.0)
        GeometryReader { geometry -> Text in
          let frame = geometry.frame(in: CoordinateSpace.global)
          self.userData.circleImageY[self.landmarkIndex] = Double(frame.midY)
          return
            Text("\(frame.midY)")
              .foregroundColor(.red)
              .bold()
              .font(.title)
        }
        .offset(x: 0.0, y: -50.0)
      }
    }
  }
}`

Not only does this save the rendered coordinates, it also renders them as a Text view overlaid with the image as suggested by Jake. Naturally you can delete the Text overlay view once you're satisfied the coordinates are correct. Hope this helps

2
struct LineView: View {
    
    @State private var viewFrames: [CGRect] = [.zero, .zero, .zero]
    @State private var path: Path? = nil
    
    var body: some View {
        ZStack{
            VStack {
                
                HStack {
                    Spacer()
                    Text("View 1")
                        .foregroundColor(.white)
                        .background(
                            GeometryReader { geometry in
                                Color.blue.onAppear {
                                    viewFrames[0] = geometry.frame(in: .global)
                                    path = createPath()
                                }
                            })
                    Spacer()
                }
                
                HStack {
                    Spacer()
                    Text("View 2")
                        .foregroundColor(.white)
                        .background(
                            GeometryReader { geometry in
                                Color.green
                                    .onAppear {
                                        viewFrames[1] = geometry.frame(in: .global)
                                        path = createPath()
                                    }
                            })
                }
                
                HStack {
                    Text("View 3")
                        .foregroundColor(.white)
                        .background(GeometryReader { geometry in
                            Color.orange
                                .onAppear {
                                    viewFrames[2] = geometry.frame(in: .global)
                                    path = createPath()
                                }
                        })
                    Spacer()
                }
                
            }
            
            if let path = path {
                path.stroke(Color.gray, lineWidth: 3)
                    .ignoresSafeArea()
            }
            
        }
    }
    
    private func createPath() -> Path? {
        // Check if all frames are set.
        guard viewFrames.allSatisfy({ !$0.isEmpty }) else {
            return nil
        }
        // Calculate the center points of each view.
        let centerPoints = viewFrames.map {
            CGPoint(x: ($0.midX), y: $0.midY)
        }
        
        // Create a path connecting the center points of each view.
        var path = Path()
        path.move(to: centerPoints[0])
        path.addLine(to: centerPoints[1])
        path.addLine(to: centerPoints[2])
        return path
    }
    
}

1

When you need a view's position outside the view itself, PreferenceKeys are a great way to pass that information up the view hierarchy.

PreferenceKeys can seem a bit daunting – but they allow to use a GemoetryReader in an overlay, preventing the GeometryReader to mess with the layout is it has a sad tendency to do.

I created this AbsolutePositionReader (usage below), inspired by this amazing blog post:

struct AbsolutePositionReader: View {
  let id: String?
  init() { self.id = nil }
  init(_ id: String?) { self.id = id }
  
  var body: some View {
    GeometryReader { metrics in
      let absolutePosition = CGPoint(
        x: metrics.frame(in: .named("AbsolutePositionReaderSpace")).midX, // use min/mid/max as needed
        y: metrics.frame(in: .named("AbsolutePositionReaderSpace")).midY  // use min/mid/max as needed
      )

      Rectangle()
        .fill(Color.clear)
        .preference(
          key: AbsolutePositionKey.self,
          value: [AbsolutePositionValue(id: id, absolutePosition: absolutePosition)]
        )
    }
  }
}

struct AbsolutePositionValue: Equatable {
  let id: String?
  let absolutePosition: CGPoint
}

struct AbsolutePositionKey: PreferenceKey {
    typealias Value = [AbsolutePositionValue]
    static var defaultValue: [AbsolutePositionValue] = []
    static func reduce(value: inout [AbsolutePositionValue], nextValue: () -> [AbsolutePositionValue]) {
        value.append(contentsOf: nextValue())
    }
}

This is how you use it to draw that line:

struct Lines: View {
  @State var box1Center: CGPoint = CGPoint()
  @State var box2Center: CGPoint = CGPoint()
  
  var body: some View {
    ZStack() {
      HStack(alignment: .top) {
        Rectangle()
          .fill(Color.blue)
          .frame(height: 100)
          .overlay(AbsolutePositionReader("box1"))
        
        Spacer()
        
        Rectangle()
          .fill(Color.red)
          .overlay(AbsolutePositionReader("box2"))
        
      }
        // Saves the positions of the boxes to the state, so we can draw the line
        .onPreferenceChange(AbsolutePositionKey.self) { preferences in
          for pref in preferences {
            if (pref.id == "box1") { box1Center = pref.absolutePosition }
            if (pref.id == "box2") { box2Center = pref.absolutePosition }
          }
        }
      
      Path { path in // Draws the actual line
        path.move(to: box1Center)
        path.addLine(to: box2Center)
      }.stroke(Color.white, lineWidth: 4)
      
    }.coordinateSpace(name: "AbsolutePositionReaderSpace")
  }
}

Result: Boxes with a line

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.