0

I need to know the current view width and height, I managed to get it using the following code but it works only if I manually select the NavigationView. I also tried to include the GeometryReader { ... } part in another view but it modifies the position of other elements. My question to you, is there a way to call NavigationView automatically (just in order to get the view sizes) and return to the main view without manual action? Or is there another way to get the current view width and height?

struct NavigationView : View {
    @ObservedObject var myMaze = Maze.sharedInstance
    var body : some View {
        GeometryReader { geometry in
            Path { path in
                myMaze.viewWidth = geometry.size.width
                myMaze.viewHeight = geometry.size.height
            }
        }
    }
}
Swiftiti
  • 49
  • 5
  • Does this answer your question https://stackoverflow.com/a/60214735/12299030? – Asperi Dec 29 '20 at 12:55
  • May be yes but where am I supposed to put the function rectReader? – Swiftiti Dec 29 '20 at 13:14
  • @Swiftiti This may help you https://stackoverflow.com/questions/60726589/with-swiftui-is-there-a-way-to-constrain-a-views-size-to-another-non-sibling-v/62279021#62279021 – Yodagama Dec 29 '20 at 13:21
  • 1
    What exactly are you trying to accomplish, what is `Maze`? – koen Dec 29 '20 at 13:57
  • Maze is a class for building a maze and I'm currently fighting with how to draw it on a view, you can see the 2 main files in https://drive.google.com/drive/folders/1FK3eYbGmpLprgpqpLcpEDEFVHJ6cN8Gt?usp=sharing – Swiftiti Dec 29 '20 at 15:01

1 Answers1

0

Give this code a try, it works in my case: For height:

view.getMeasuredHeight()

For width:

view.getMeasuredWidth()

Note: this code won't work in onCreate because the view hasn't been drawn yet, add a listener or a timer depending on your needs.

Ilyasse Salama
  • 367
  • 3
  • 16
  • I tried to put it inside init() but I get the error "Value of type 'MapView' has no member 'getMeasuredWidth'". How can I implement it? I don't know how to use listener or a timer. – Swiftiti Dec 29 '20 at 13:24
  • Let's say you want to use a timer. You can start the timer to get every 100ms the height and width of your view. – Ilyasse Salama Dec 29 '20 at 14:40