Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift: Move animation

Tags:

ios

swift

I have viewController in storyboard. And 4 squares. I want to place my squares on view. At first I want to show two squares. If I press on button I want to my red 2 squares move left and I show next 2 blue squares. Like this animation.

enter image description here

Do I need to create a scrollView or collectionView or something else to move the squares? What the best way to create this?


1 Answers

Use UiVew.animate and CGAffineTransform

Setup

Create a UIView that will contain your squares. Make sure that UIView has clip to bounds enabled. Then, add your four squares in, with the blue ones nested inside the UIView, but with their coordinates outside of the container so that they're getting clipped.

View of Storyboard editor

Then, when you want to move them, you simply translate all of your squares x to the left. By putting this movement inside of a UIView.animate block, iOS will perform the animation for you.

UIView.animate(withDuration: 2.0) {
    self.redTopView.transform = CGAffineTransform(translationX: -160, y: 0)
    self.redBottomView.transform = CGAffineTransform(translationX: -160, y: 0)
    self.blueTopView.transform = CGAffineTransform(translationX: -160, y: 0)
    self.blueBottomView.transform = CGAffineTransform(translationX: -160, y: 0)
}

Final result: http://g.recordit.co/SToMSZ77wu.gif

like image 139
Serdnad Avatar answered Sep 03 '25 14:09

Serdnad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!