SALE: Save 50% on all my books and bundles >>

How to create a custom transition

Paul Hudson    @twostraws   

Fully updated for Xcode 11.4

Although SwiftUI comes with a selection of transitions built in, it’s also possible to write entirely custom transitions if we want to.

The process takes three steps:

  1. Create a ViewModifier that represents your transition at any of its states.
  2. Create an AnyTransition extension that uses your view modifier for active and identity states.
  3. Apply that transition to your views using the transition() modifier.

For example, we could write a shape and view modifier combination that lets us mimic the Iris animation in Keynote – it causes a new slide to appear in a circle that grows upwards, a bit like the old Looney Tunes intro sequence.

To make this work we need to define a ScaledCircle shape that creates a circle inside a rectangle that is scaled according to some animatable data:

struct ScaledCircle: Shape {
    var animatableData: CGFloat

    func path(in rect: CGRect) -> Path {
        let maximumCircleRadius = sqrt(rect.width * rect.width + rect.height * rect.height)
        let circleRadius = maximumCircleRadius * animatableData

        let x = rect.midX - circleRadius / 2
        let y = rect.midY - circleRadius / 2

        let circleRect = CGRect(x: x, y: y, width: circleRadius, height: circleRadius)

        return Circle().path(in: circleRect)
    }
}

As you can see, that exposes a single animatableData property that controls the size of the circle inside the drawing rectangle. So, when animatableData is 0 the circle is invisible, and when it’s 1 the circle fills the rectangle.

We can now create a custom ViewModifier struct to apply any shape (in our case, the scaled circle) as a clip shape for another view:

struct ClipShapeModifier<T: Shape>: ViewModifier {
    let shape: T

    func body(content: Content) -> some View {
        content.clipShape(shape)
    }
}

Next, we can make an AnyTransition extension to wrap that modifier in a transition for easier access:

extension AnyTransition {
    static var iris: AnyTransition {
        .modifier(
            active: ClipShapeModifier(shape: ScaledCircle(animatableData: 0)),
            identity: ClipShapeModifier(shape: ScaledCircle(animatableData: 1))
        )
    }
}

Finally, we can use that transition with .transition(.iris). As an example, this creates a ZStack with a blue rectangle, over which we slide in a red rectangle when the “Switch” button is tapped:

struct ContentView: View {
    @State private var isShowingRed = false

    var body: some View {
        NavigationView {
            ZStack {
                Rectangle()
                    .fill(Color.blue)
                    .frame(width: 300, height: 300)

                if isShowingRed {
                    Rectangle()
                        .fill(Color.red)
                        .frame(width: 300, height: 300)
                        .transition(.iris)
                        .zIndex(1)
                }
            }
            .navigationBarItems(trailing: Button("Switch") {
                withAnimation(.easeInOut) {
                    self.isShowingRed.toggle()
                }
            })
        }
    }
}
Hacking with Swift is sponsored by RevenueCat

SPONSORED Building in-app subscriptions are hard – especially cross-platform. RevenueCat makes it simple. With their native SDKs, you can implement a custom subscription model for your app in hours, not months.

Explore the docs to learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Cascable unleashes the power of your camera and unlocks powerful workflows for shooting, managing, and geotagging your photos.

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!