Blog

Animating Explicit Changes

In SwiftUI, there are multiple ways to animate changes to your views. In Swift Talk Episode 165, we showed how to animate a shape along a path, by building a custom shape that conforms to the Animatable protocol.

Here's the relevant animation code:

								struct ContentView: View {
    @State var position: CGFloat = 0
    // ...
    var body: some View {
        VStack {
            ZStack {
                // ...
                OnPath(shape: rect, pathShape: Eight(), offset: position)
                    .foregroundColor(.black)
                    .animation(Animation.linear(duration: 5).repeatForever(autoreverses: false))
            }
            .onAppear(perform: {
                self.position = 1
            })
            // ...
        }
    }
}

							

We wanted to animate the position from 0 to 1 whenever the view appears, and repeat this animation forever, with the shape animating along the path indefinitely. When we run the application, the animation looks like this:

However, there's a problem with the code. When we rotate the device, it animates in a very strange way:

Currently, our OnPath shape gets animated implicitly whenever anything it depends on changes: the position, its container size, and so forth. To fix this problem, we need to make sure that our animation only applies to changes to the position property.

Instead, we should rewrite our code like this:

								struct ContentView: View {
    @State var position: CGFloat = 0
    // ...
    var body: some View {
        VStack {
            ZStack {
                // ...
                OnPath(shape: rect, pathShape: Eight(), offset: position)
                    .foregroundColor(.black)

            }
            .onAppear(perform: {
                withAnimation(Animation.linear(duration: 5).repeatForever(autoreverses: false)) {
                    self.position = 1
                }
            })
            // ...
        }
    }
}

							

Now, we're only adding the repeating path animation when the position changes, which only happens when the view appears. Rotating the device no longer influences the infinite animation.

If you'd like to learn alongside us as we experiment with SwiftUI, we have a growing Swift Talk Collection, with a new episode added every week. Episodes 156: A First Look at SwiftUI, 158: The Swift Talk App, and 167: Building a Collection View are free to watch.

To watch the entire SwiftUI collection, subscribe here.

  • Watch the Full Episode

  • See the Swift Talk Collection

Stay up-to-date with our newsletter or follow us on Twitter .

Back to the Blog

Recent Posts