Swift version: 5.10
Believe it or not, iOS has a built-in particle system that works great in all UIKit apps and is immensely customizable. To get started you need to create a CAEmitterLayer
object and tell it how to create particles: where it should create them, how big the emitter should be, and what types of particles should exist.
The "type of particles" part is handled by CAEmitterCell
, which covers details like how fast to create, how long they should live, whether they should spin and/or fade out, what texture to use, and more. You can add as many CAEmitterCells
to a CAEmitterLayer
as you need.
Here's some example code to get you started. This creates particles of three different colors, all falling and spinning down from the top of the screen. The image "particle_confetti" is just a small white triangle that I drew by hand – you should replace that with something more interesting.
func createParticles() {
let particleEmitter = CAEmitterLayer()
particleEmitter.emitterPosition = CGPoint(x: view.center.x, y: -96)
particleEmitter.emitterShape = .line
particleEmitter.emitterSize = CGSize(width: view.frame.size.width, height: 1)
let red = makeEmitterCell(color: UIColor.red)
let green = makeEmitterCell(color: UIColor.green)
let blue = makeEmitterCell(color: UIColor.blue)
particleEmitter.emitterCells = [red, green, blue]
view.layer.addSublayer(particleEmitter)
}
func makeEmitterCell(color: UIColor) -> CAEmitterCell {
let cell = CAEmitterCell()
cell.birthRate = 3
cell.lifetime = 7.0
cell.lifetimeRange = 0
cell.color = color.cgColor
cell.velocity = 200
cell.velocityRange = 50
cell.emissionLongitude = CGFloat.pi
cell.emissionRange = CGFloat.pi / 4
cell.spin = 2
cell.spinRange = 3
cell.scaleRange = 0.5
cell.scaleSpeed = -0.05
cell.contents = UIImage(named: "particle_confetti")?.cgImage
return cell
}
SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 5.0 – see Hacking with Swift tutorial 37
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.