Creating a Flip Card animation with UICollectionViewCell (Swift 3.0)
I am in the midst of doing a very simple memory card game and I thought of adding a flip animation to every single card that is being tapped. There are many ways we can achieve this, one of the simplest but brute force way is to already have in mind how many rows and cards we need, then we just add as many animated imageviews as required. But for the purpose of this post, I will be writing on how to achieve it with UICollectionView, I am running Xcode 8 with Swift 3.0 syntax.
Firstly, create a new project, I call my project “FlipCollectionViewCell”, and set it to landscape :
I added a UICollectionViewController, embedded it in a navigation controller and set that as Initial View Controller in the storyboard. Next I created a “FCGameCardCollectionViewCell”, subclass of UICollectionViewCell with an empty xib. You don’t have to do anything to it. I fixed my card size to 165 by 240. So I set them inside my storyboard and gave a bit of spacings between items and lines :
Next, its time to setup some collection views in the controller :
I generated 4 rows of 8 card each using iPad Pro 12.9 inch :
Next, I setup these 2 delegate methods :
Take note that in didSelectItemAt, we should call cellForItem as we want to animated the already populated cell in view and not the one in memory. So lets see now how do we wire up the flipCardAnimation() method!
In the FCGameCardCollectionViewCell :
The first thing I did is to create tag numbers to differentiate the imageViews (front/back), create a tuple data structure to hold the front and back views, then create 2 variables for each UIImageViews :
Next, I initialise the imageviews in awakeFromNib() as we registered the collectionview as nib before :
Next the main ingredient to create the flip animation is finally here ! :
Firstly, check if the backview is in the contentView by calling its superview, then create a transitionOption variable to set the flip animation. Finally, all the UIView.transition method to let it do the work :
- Set context to be the cell.contentView
- Then always remove the backview and add the front view every time the animation is called because we are always alternating the views
- Viola! We created our first flip animation, now we are ready to add the game logic
This short post is just to guide you on how to create the animation, next challenge is to create the memory game logic!
You may see my full project here in my github!
Before you go…
If you enjoyed this post, you will love Lawrey Swifty Weekly. It’s my FREE weekly digest of the best iOS-related nuggests and stuffs about life, productivity and self improvement. Subscribe here. Join readers around the world to be more swifty!