简体   繁体   English

Swift:动画UIView朝着源而不是远离源

[英]Swift: Animated UIView moves towards source instead of away from it

I seriously looked around here but didn't find something that would answer my question, so if you found a right solution, please tell me. 我认真地环顾四周,但找不到能回答我问题的内容,因此,如果您找到正确的解决方案,请告诉我。

So: I wrote a little app in Xcode in which two labels should move from there current position to a another position 350 points above. 所以:我用Xcode编写了一个小应用程序,其中两个标签应该从当前位置移动到上方350点的另一个位置。 I animated them like this: 我像这样对它们进行动画处理:

UIView.animate(withDuration: 2.0 , animations: {            
    self.label1.center.y += CGFloat(-350)
    self.label2.center.y += CGFloat(-350)
})

What actually happened was, that as soon as this line was hit, the labels jumped 350 points down and then moved the 350 points up to their source. 实际发生的是,只要碰到这条线,标签就会跳下350点,然后再将350点向上移动到其源头。 When I changed the CGFloat value to +350, the labels jumped up 350 points, and then moved down back to source again. 当我将CGFloat值更改为+350时,标签跳了350点,然后又移回了源。 So it seems, instead of starting the animation from the source, Xcode tried to make the animation go to the source. 如此看来,Xcode并非从源头开始制作动画,而是尝试使动画进入源代码。 I honestly do not have a clue why, as all the documentation about animation suggest otherwise. 老实说,我不知道为什么,因为有关动画的所有文档都建议这样做。

BTW I also looked, whether I had a constraint on the y-placement of the labels, but there weren't any. 顺便说一句,我还看了看我是否对标签的y位置有约束,但没有任何约束。

First, try: 第一次尝试:

self.label1.center.y += CGFloat(-350)
self.label2.center.y += CGFloat(-350)

Then: 然后:

UIView.animate(withDuration: 2.0 , animations: {
    layoutIfNeeded()
}

Note: If you use constraints for labels you should change your labels' positions by changing their constraints instead of adding CGFloat to it. 注意:如果对标签使用约束,则应通过更改其约束而不是向其添加CGFloat来更改其位置。 Then try: 然后尝试:

UIView.animate(withDuration: 2.0 , animations: {
    layoutIfNeeded()
}

Instead of trying to move the center of the view which is kind of bad practice, you can try the following code in you animation block 可以尝试在动画块中尝试以下代码,而不是尝试移动视图的中心(这是一种不好的做法)

self.label2.transform = CGAffineTransform(scaleX: 0, y: 350)

This will actually animate the layer and not the actual frame of the view. 这实际上将为图层设置动画,而不是视图的实际框架。

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

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