[SwiftUI] Animation / Transition Text changes using .id modifier

Updated
Aug 7, 2020 7:03 PM
Created
Aug 7, 2020 6:36 PM
Tags
SwiftSwiftUI
Keywords
Date

public struct AnimateText: View {

  let text: String

  public var body: some View {
    Text(text)
      .id(text)
      .font(Font.system(size: 50).monospacedDigit())
      .transition(.opacity)
  }

}

public struct AnimateText: View {

  let text: String

  public var body: some View {
    Text(text)
      .id(text)
      .font(Font.system(size: 200, weight: .bold, design: .default).monospacedDigit())
      .transition(
        AnyTransition.modifier(
          active: SwapModifier(isActive: true),
          identity: SwapModifier(isActive: false)
        )
        .animation(.spring(response: 0.4, dampingFraction: 0.9, blendDuration: 0))
      )
  }

}

struct SwapModifier: ViewModifier {

  let isActive: Bool

  func body(content: Content) -> some View {
    content
      .scaleEffect(isActive ? 3 : 1)
      .opacity(isActive ? 0 : 1)
      .blur(radius: isActive ? 10 : 0)
  }
}

Refs