hbtpoprock
hbtpoprock

Reputation: 103

Swift UIView Animate doesn't work properly

Slide up animation will be triggered when a button is clicked.

    func animation_onClick(action: String) {
          let up = CGAffineTransform(translationX: 0, y: -30)

          myView.transform = CGAffineTransform(translationX: 0, y: 0)

          UIView.animate(withDuration: 0.5, delay: 0.0, options: [], animations: {
              self.myView.transform = up            
          }, completion: nil)
    }

My code means when the function runs, myView’s position will be set to (0, 0) referring to its original position every time before it was set to (0, -30).

But when I run the app, I repeatedly click the button, somehow myView doesn't go back to its origin, it goes below where it should be. What I mean is it's not supposed to go below its origin.

See the gif below.

enter image description here

Upvotes: 0

Views: 166

Answers (1)

Asperi
Asperi

Reputation: 257779

Try the following

func animation_onClick(action: String) {
    myView.layer.removeAllAnimations()
    myView.transform = .identity

    UIView.animate(withDuration: 0.5, delay: 0.0, options: [], animations: {
        self.myView.transform = CGAffineTransform(translationX: 0, y: -30)
    }, completion: nil)
}

Upvotes: 0

Related Questions