7

I'd like to calculate the line width of a shape inside a view based on the view's size. Looking through various posts here on StackOverflow, I think the solution is to use a GeometryReader like this:

struct MyView: View {
    var body: some View {
        GeometryReader { geometry in
           // Here goes your view content,
           // and you can use the geometry variable
           // which contains geometry.size of the parent
           // You also have function to get the bounds
           // of the parent: geometry.frame(in: .global)
        }
    }
}

My question is, how can I define variables inside the GeometryReader construct to be used for the view? I've tried to put a var statement directly after the line "GeometryReader { geometry in", but this gives a compiler error.

3
  • Clarification: are you trying to find the dimensions of MyView, or its parent? Is MyView the "line width of a shape" (where GeometryReader would be the dimensions of the parent view) or is this "shape" a child View inside MyView? Commented Jul 16, 2019 at 22:19
  • Basically, don't forget the everything in SwiftUI is a View - it sounds like you are trying to work with a CAShapeLayer frame based on the UIView dimensions. Commented Jul 16, 2019 at 22:20
  • The answer bellow just solves what I'm trying to achieve. Thanks. Commented Jul 17, 2019 at 7:05

1 Answer 1

16

This seems to be a function builder related bug (as of Beta 3), and I recommend filing feedback on it.

The workaround I've been using is to use GeometryProxy in a separate method with an explicit return.


var body: some View {
  GeometryReader { proxy in
    self.useProxy(proxy)
  }
}

func useProxy(_ proxy: GeometryProxy) -> some View {
  var width = proxy.size.width
  return VStack {
    // use width in here
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I believe I'm still seeing this in beta 7.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.