How do I use CADisplayLink for smooth animations in Swift?

CADisplayLink is an integral part of smooth animations in iOS development using Swift. It provides a timer that synchronizes your drawing code to the refresh rate of the display, ensuring your animations are fluid and visually appealing.

Using CADisplayLink allows you to create frame-based animations seamlessly. Here’s a simple example of how to set it up:

import UIKit class ViewController: UIViewController { var displayLink: CADisplayLink! var squareView: UIView! override func viewDidLoad() { super.viewDidLoad() squareView = UIView(frame: CGRect(x: 100, y: 100, width: 50, height: 50)) squareView.backgroundColor = .blue view.addSubview(squareView) // Initialize and set up CADisplayLink displayLink = CADisplayLink(target: self, selector: #selector(update)) displayLink.add(to: .current, forMode: .default) } @objc func update() { // Update your animation here squareView.center.x += 1 // Move the square if squareView.center.x > view.bounds.width { squareView.center.x = 0 // Reset position } } deinit { displayLink.invalidate() // Clean up the display link } }

CADisplayLink animations Swift iOS development fluid animations UIView