user3069232
user3069232

Reputation: 8995

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?

Upvotes: 2

Views: 4513

Answers (2)

Haseeb Javed
Haseeb Javed

Reputation: 2054

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

Upvotes: 0

nine stones
nine stones

Reputation: 3438

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.

Upvotes: 3

Related Questions