Animations can greatly improve a user’s experience when interacting with a mobile application. In this tutorial, I will show you how to recreate a very simple animation most of us are familiar with: Instagram’s “like” animation.

Instagram’s “like” animation.

Let’s start by adding the heart icon assets we’re going to be using in our Xcode project. One is white and the other red (I usually find great icons on Icons8).

Assets folder in Xcode

Now let’s create a class for our button. We will call it HeartButton and will make it a subclass of UIButton. Let’s start by just setting the initial image to the empty heart.

import UIKit

	class HeartButton: UIButton {

	  private let unlikedImage = UIImage(named: "heart_empty")
	  private let likedImage = UIImage(named: "heart_filled")

	  override public init(frame: CGRect) {
	    super.init(frame: frame)

	    setImage(unlikedImage, for: .normal)
	  }

	  required init?(coder: NSCoder) {
	    fatalError("init(coder:) has not been implemented")
	  }
	}

If you add a HeartButton to your app and run it, it will look something like this:

Let’s add some code to keep track of the state of the button, as well as a method to flip this state and animate the button accordingly. The animation itself consists of two main steps:

  • Step one: When the button is pressed, we scale the button down (using the scale transform) and flip the heart image.
  • Step two: When the animation has finished, we return the button to its original scale (we do this by applying the [identity](https://developer.apple.com/documentation/coregraphics/cgaffinetransform/1455180-identity) transform).

We will achieve these steps by using [UIView.animate](https://developer.apple.com/documentation/uikit/uiview/1622515-animate), where the animation block will execute step one above and the completion block will execute step two in an animation of itself:

import UIKit

	class HeartButton: UIButton {
	  private var isLiked = false

	  // ...

	  public func flipLikedState() {
	    isLiked = !isLiked
	    animate()
	  }

	  private func animate() {
	    // Step 1
	    UIView.animate(withDuration: 0.1, animations: {
	      let newImage = self.isLiked ? self.likedImage : self.unlikedImage
	      self.transform = self.transform.scaledBy(x: 0.8, y: 0.8)
	      self.setImage(newImage, for: .normal)
	    }, completion: { _ in
	      // Step 2
	      UIView.animate(withDuration: 0.1, animations: {
	        self.transform = CGAffineTransform.identity
	      })
	    })
	  }
	}

Now, when your button is tapped, you can call the flipLikedState method to execute the animations.

#programming #ios #mobile #swift #xcode

Recreating Instagram’s Like ❤️Animation in Swift
22.75 GEEK