Swift code for bubble animation (iOS)

Mr.Javed Multani
1 min readJun 14, 2023

--

Here’s an example of Swift code for a simple bubble animation using UIViewPropertyAnimator:

import UIKit

class ViewController: UIViewController {
let bubbleView = UIView()

override func viewDidLoad() {
super.viewDidLoad()

// Set up the bubble view
bubbleView.frame = CGRect(x: 150, y: 200, width: 100, height: 100)
bubbleView.layer.cornerRadius = 50
bubbleView.backgroundColor = UIColor.blue
view.addSubview(bubbleView)

// Start the bubble animation
animateBubble()
}

func animateBubble() {
let animator = UIViewPropertyAnimator(duration: 2.0, dampingRatio: 0.5) {
// Specify the animation changes
self.bubbleView.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
}

animator.addCompletion { _ in
// Animation completed, reset the bubble view
self.bubbleView.transform = CGAffineTransform.identity
self.animateBubble() // Repeat the animation
}

animator.startAnimation()
}
}

In this example, a bubble view is created as a blue circle with a rounded shape. The animateBubble() function creates a UIViewPropertyAnimator that animates the scaling of the bubble view to make it larger (scale factor of 1.5) over a duration of 2 seconds. After the animation completes, the completion block is executed, resetting the bubble view's transform back to the original scale and then calling animateBubble() again to repeat the animation in a loop.

Please note that you need to have a UIViewController subclass and add the necessary views to your view hierarchy for this code to work properly.

Get in touch with me:

https://www.linkedin.com/in/javedmultani16/

--

--

Mr.Javed Multani

Software Engineer | Certified ScrumMaster® (CSM) | UX Researcher | Youtuber | Tech Writer