0
0
iOS Swiftmobile~5 mins

Custom animation timing in iOS Swift

Choose your learning style9 modes available
Introduction

Custom animation timing lets you control how fast or slow an animation plays at different moments. This makes animations feel smooth and natural.

When you want a button to bounce gently instead of moving at a constant speed.
When you want a view to fade in slowly at first, then quickly at the end.
When you want to create a spring effect for a popup appearing on screen.
When you want to slow down an animation in the middle to draw attention.
When you want to match animation speed with sound or other effects.
Syntax
iOS Swift
UIView.animate(withDuration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions, animations: @escaping () -> Void, completion: ((Bool) -> Void)? = nil)

The options parameter lets you set timing curves like .curveEaseIn, .curveEaseOut, or .curveLinear.

For more custom control, use CAMediaTimingFunction with Core Animation layers.

Examples
Simple fade out animation with default timing.
iOS Swift
UIView.animate(withDuration: 1.0, animations: {
  view.alpha = 0
})
Animation that starts slowly and speeds up.
iOS Swift
UIView.animate(withDuration: 1.0, delay: 0, options: .curveEaseIn, animations: {
  view.frame.origin.y += 100
}, completion: nil)
Animation that starts fast and slows down at the end.
iOS Swift
UIView.animate(withDuration: 1.0, delay: 0, options: .curveEaseOut, animations: {
  view.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
}, completion: nil)
Sample App

This code creates a blue square and moves it down while fading it out. The animation speeds up at the start and slows down at the end for a smooth effect.

iOS Swift
import UIKit

class ViewController: UIViewController {
  let box = UIView()

  override func viewDidLoad() {
    super.viewDidLoad()
    box.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
    box.backgroundColor = .systemBlue
    view.addSubview(box)

    // Animate with custom timing curve
    UIView.animate(withDuration: 2.0, delay: 0, options: .curveEaseInOut, animations: {
      self.box.frame.origin.y += 200
      self.box.alpha = 0.5
    }, completion: nil)
  }
}
OutputSuccess
Important Notes

Use .curveEaseInOut for smooth start and end.

For very custom timing, explore CAMediaTimingFunction and CAKeyframeAnimation.

Remember to test animations on real devices for best feel.

Summary

Custom animation timing controls how animation speed changes over time.

Use UIView animation options like .curveEaseIn and .curveEaseOut for simple timing changes.

For advanced control, use Core Animation timing functions.