简体   繁体   English

iOS Swift UIView animation 跳回到开头

[英]iOS Swift UIView animation jumps back to the beginning



I am quite new to swift and have a little problem.我对 swift 很陌生并且有一点问题。 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.我正在制作一个小游戏,里面有一个 UIView。 I animate it to a random position on the screen using UIView.animate().我使用 UIView.animate() 将其动画到屏幕上的随机 position。 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.问题是,当我用另一个视图制作另一个 animation 时,之前的动画视图会跳回到屏幕上的初始 position。

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.例如,如果名为 Skull 的 UIView 在 storyboard 中被限制为 x: 50 和 y: 200,并且我将其设置为 x: 120、y: 400 的动画,则它可以找到并正确设置动画。 But when I press the pause Button, which has a little scale animation when clicked, the skull jumps back to x: 50, y: 200.但是当我按下暂停按钮时,点击时有一点刻度 animation,头骨跳回到 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.我真的不确定我做错了什么,也许是自动布局的问题,但就像我说的,我是 swift 的新手,互联网也帮不了我。

So thanks for any help in advance!所以提前感谢您的帮助!

You need to layout subview in Animation like this您需要像这样在 Animation 中布局子视图

      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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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