Search code examples
iosswiftviewswiftui

SwiftUI changing the position of a view programmatically


Swift 5, iOS 13

A SwiftUI question

I want to record the position of a view when it is created. I want to save the position cause I want the ability to move it back there if I hit the reset button. The view in question is drag-able. I can use the Geometry reader to pickup its co-ordinates when I create it, setting them with the .appear attribute. And I can use the position attribute to place it at point X.

But if I use the position I need to give it co-ordinates. And if I give it co-ordinates I cannot place it using something sane like a HStack. I need the position attribute ignored the first time it runs, and then applied every time subsequently.

It feels like a chicken and egg problem. Has anybody solved this? A wild thought, can I use offset perhaps?


Solution

  • To me, your wild guess of using the .offset(x:y:) modifier seems to put you on the right track.

    Grab the position from the GeometryReader proxy of the view in question in .onAppear{} and restore it using the .offset.

    This earlier answer of mine does this using the x-axis only, should be easy enough to apply it to the y-axis as well : https://stackoverflow.com/a/60854527/301790

    If you need more guidance consider posting code ready to copy-and-paste into Xcode.