简体   繁体   中英

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. 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. When I changed the CGFloat value to +350, the labels jumped up 350 points, and then moved down back to source again. So it seems, instead of starting the animation from the source, Xcode tried to make the animation go to the source. 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.

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. 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.

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