简体   繁体   中英

iOS Swift UIView animation jumps back to the beginning



I am quite new to swift and have a little problem. I searched the internet for hours now and couldn't find any solution, so this is my last hope!

I am making a little game and in there I have an UIView. I animate it to a random position on the screen using UIView.animate(). The problem is, when I make another animation with another view, the previously animated view jumps back to it's initial position on the screen.

This is the code which I use to animate the views:

UIView.animate(withDuration: 1.0, delay: 0.0, options: .curveEaseInOut, animations: {
            self.skull.frame = CGRect(x: xSkull, y: ySkull, width: self.skull.frame.size.width, height: self.skull.frame.size.height)
        }, completion: nil)


For example, if the UIView called skull is constrained in the storyboard to x: 50 and y: 200, and I animate it eg to x: 120, y: 400, it works find and is animated correctly. But when I press the pause Button, which has a little scale animation when clicked, the skull jumps back to x: 50, y: 200.

When I try to animate the constants of the constraints of the view, it just jumps and doesn't animate at all:

UIView.animate(withDuration: 1.0, delay: 0.0, options: .curveEaseInOut, animations: {
            self.skull_xConstraint.constant = xSkull
            self.skull_yConstraint.constant = ySkull
        }, completion: nil)



I am really not sure what I did wrong, maybe something with the autolayout, but like I said, I am new to swift and the internet couldn't help me either.

So thanks for any help in advance!

You need to layout subview in Animation like this

      self.skull_xConstraint.constant = xSkull
      self.skull_yConstraint.constant = ySkull
      UIView.animate(withDuration: 1.0, delay: 0.0, options: .curveEaseInOut, animations: {
           self.view.layoutIfNeeded()
        }, completion: nil)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM