2

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?

1
  • Would you show your tries in code? Commented Apr 11, 2020 at 15:17

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, thanks for your confirmation. In fact I had the figures. I was using offset to store the drag value, all I needed to do was reset that and everything returned to its original place, no need for the Geometry reader this time, but next.
0

Here the code example of a UIButton

 Button(action: {
        //Here what you want to do on button click:
 }) {
 HStack {
 Spacer()
 Text("Scores")
 Spacer()
 }
 }.frame(width: 90, height: 45, alignment: .center)
           .foregroundColor(Color.white)
           .background(Color.black)
           .contentShape(Rectangle())
           .padding(EdgeInsets(top: 16, leading: 
            UIScreen.main.bounds.size.width - 110 , bottom: 16, trailing: 20))

UIScreen.main.bounds.size.width is to get screen width and then you can minus the button width from it to adjust it to right corner. Shown in attached image: Ref. Image

Comments

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.