-1

I have the following code to swipe a view out of the screen when swiped right

let gesture = UISwipeGestureRecognizer(target: self, action: #selector(swipedView(_:)))
gesture.direction = .right
centerView.addGestureRecognizer(gesture)

@objc func swipedView(_ sender: UISwipeGestureRecognizer) {
    UIView.animate(withDuration: 2.0, animations: {
        centerView.frame = centerView.frame.offsetBy(dx: self.view.frame.maxX-centerView.frame.minX, dy: 0)
    }) { completed in
    //Call API and if response failed move centerView to its original position
    } 
}

In animation's completion block I call an API. If the response is failed, I want to move centerView to its initial position. How can I do this without saving the starting frame in another variable?

Joshua Cleetus
  • 624
  • 6
  • 14
iOSDev
  • 326
  • 2
  • 10

2 Answers2

0

Keep track of the original location before you move it.

var lastLocation: CGPoint?

// later
lastlocation = centerView.frame.origin
centerView.frame = centerView.frame.offsetBy(dx: self.view.frame.maxX-centerView.frame.minX, dy: 0)

Then whenever you would like to move it back just do the same again

UIView.animate(withDuration: 2.0) {
    if let point = self.lastLocation {
        self.centerView.frame.origin = point
    }
}
Scriptable
  • 19,402
  • 5
  • 56
  • 72
  • 1
    *How can I do this without saving the starting frame in another variable?* – えるまる Sep 12 '19 at 16:03
  • 1
    Well I don't think you can, you want to remember where it was to return to that point later unless it's starting position is already a known value. I.e. if your using auto layout for example and have a constraint constant starting out at zero, then you move it some amount, later you can just reset it back to zero – Scriptable Sep 13 '19 at 07:47
0

As mentioned in the other answer, I'd use a var to record its initial position. However, if you insist to do it differently, then I guess it's possible, assuming that centerView is always supposed to be centered horizontally in self.view.

// Call API and if response failed move centerView to its original position
centerView.center.x = self.view.bounds.midX // y-value never changed so no need to change it here