Your First iOS & SwiftUI App: Polishing the App

Mar 1 2022 · Swift 5.5, iOS 15, Xcode 13

Part 3: A Custom Alert

28. Intro to SwiftUI Animation

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 27. Display a Custom Alert Next episode: 29. Avoid Magic Numbers
Transcript: 28. Intro to SwiftUI Animation

Our custom alert is looking great, but currently when it appears or disappears, it’s really jarrring.

One moment it’s not there, the next moment BAM - an alert right in your face!

When developing iOS apps, it’s a best practice that whenever your user interface changes, you should add a nice animation that transitions from the old look to the new look.

That gives your users an indicator that something is changing, and that change feels more natural, and makes the app feel more delightful to use.

Luckily, SwiftUI makes animating your views extremely easy. Let’s dive into Xcode so I can show you how it works.

Open Shapes.swift, and modify as follows:

struct Shapes: View {
  @State private var wideShapes = true

  var body: some View {
    VStack {
      if !wideShapes {
        Circle()
          .strokeBorder(Color.blue, lineWidth: 20.0)
          .frame(width: wideShapes ? 200 : 100, height: 100)
      }
      RoundedRectangle(cornerRadius: 20)
        .fill(Color.blue)
        .frame(width: wideShapes ? 200 : 100, height: 100)
      Capsule()
        .fill(Color.blue)
        .frame(width: wideShapes ? 200 : 100, height: 100)
      Ellipse()
        .fill(Color.blue)
        .frame(width: wideShapes ? 200 : 100, height: 100)
      Button(action: {
        wideShapes.toggle()
      }) {
        Text("Animate!")
      }
    }
    .background(Color.green)
  }
}

Run in preview mode, tap the button.

Make RoundedRectangle animated:

.animation(.easeInOut)

Delete that line, then add this to the button:

withAnimation{
  wideShapes.toggle()
}

Add this to the circle shape:

.transition(.scale)

Also show .slide and .opacity, and leave it on .opacity.

Now that you understand the basics of animation in SwiftUI, let’s think about how we can apply it to Bullseye.

Currently, whenever we toggle the state variable alertIsVisible, this causes us to recalculate the body of ContentView. This causes three view transitions: the HitMeButton and SliderView transitions out, and the PointsView transitions in.

So to make this animated, we need to do two things:

  • First, whenever we change alertIsVisible, we should use “with animation” to indicate that we want to animate the changes that occur to the view once the button is tapped.
  • Second, we should apply the transitions that we’d like to the 3 views.

Let’s give this a try.

Add to HitMeButton:

withAnimation {
  alertIsVisible = true
}

Add to PointsView.swift:

withAnimation {
  alertIsVisible = false
}

Add to PointsView, HitMeButton, and SliderView:

.transition(.scale)