100 Days of SwiftUI

Day 33

2026-05-21

Project 6, part 2

More advanced animations (such as gestures and transitions)

Controlling the animation stack

  • remember that modifier order on a View matters
  • remember also that an animation() modifier will implicity animate changes to the view
  • .animation() will affect every view above it
    • up to the previous animation
  • therefore you can stack animations within the modifier stack to get complex animations
  • you can pass nil to the animation modifier, e.g. .animation(nil, value: someValue)
    • probably a good way to change your mind about whether or not it should be animated

Animating gestures

  • taps, drags, etc
  • CGSize is from Apple framework Core Graphics
  • Swift has the offset() modifier to allow us to move a view around without moving other views around it
    • it can take a CGSize
  • gesture() modifier goes on the view that’s going to move
    • DragGesture() has 2 closures, for example:
.gesture(
    DragGesture()
        .onChanged { dragAmount = $0.translation }
        .onEnded { _ in dragAmount = .zero }
)

// relies on this: @State private var dragAmount = CGSize.zero

Oh yeah you can make fun (and really annoying) stuff happen!

Showing and hiding views with transitions

  • works with conditionals to make view changes look nice
  • .transition() modifier
    • can be asymmetric: .transition(.asymmetric(insertion: .scale, removal: .opacity))

Building custom transitions using ViewModifier

  • pretty straightforward to make your own transitions
  • say, for example, you want to fix an anchor point for a rotation
    • use a UnitPoint
  • create a ViewModifier, then extend AnyTransition to create the easier-to-use modifier

I’m reminded of this everlasting line: