SwiftUI: Animation

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

Part 1: Beginning with SwiftUI Animation

07. Multiple Stages

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: 06. Spinner Next episode: 08. Interactive Animations

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

As always, remember that all layout changes on screen in SwiftUI are triggered by changes to your state. Currently, you have a single state property which sets which leaf is currently animated.

  @State var currentIndex = -1
  🟩@State var completed = false
  
  var body: some View {
  func animate() {
    var iteration = 0

    Timer.scheduledTimer(withTimeInterval: 0.15, repeats: true) {
      currentIndex = (currentIndex + 1) % leavesCount

      iteration += 1
    }
      iteration += 1
      if iteration == 30 {
        timer.invalidate()
        completed = true
      }
    }
    let isCurrent: Bool
    let isCompleting: Bool

    var body: some View {
            isCurrent: index == currentIndex,
            isCompleting: completed
          )
        .scaleEffect(isCurrent ? 0.5 : 1)
        🟩.rotationEffect(isCompleting ? .zero : rotation)
        🟩.animation(.easeIn(duration: 1.5), value: isCompleting)
        .animation(.easeIn(duration: 1.5), value: isCurrent)
        .stroke(isCurrent ? Color.white : .gray, lineWidth: 8)
        🟩.frame(width: 20, height: isCompleting ? 20 : 50)
        .offset(
        completed = true
        currentIndex = -1
      }
  @State var completed = false
  @State var isVisible = true
  
  var body: some View {
  var body: some View {
    VStack {
      if isVisible {
        ZStack {
          ForEach(0..<leavesCount) { index in
            Leaf(
              rotation: .init(degrees: .init(index) / .init(leavesCount) * 360),
              isCurrent: index == currentIndex,
              isCompleting: completed
            )
          }
        }
        .onAppear(perform: animate)
      }
    }
  }
currentIndex = -1
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
  isVisible = false
}
withAnimation {
  isVisible = false
}
  @State var isVisible = true

  let shootUp =
    AnyTransition.offset(x: 0, y: -1000)
  
  var body: some View {
    AnyTransition.offset(x: 0, y: -1000)
    .animation(.easeIn(duration: 1))
  
  var body: some View {
        }
        .transition(shootUp)
        .onAppear(perform: animate)