Book Image

SwiftUI Cookbook - Second Edition

By : Giordano Scalzo, Edgar Nzokwe
Book Image

SwiftUI Cookbook - Second Edition

By: Giordano Scalzo, Edgar Nzokwe

Overview of this book

SwiftUI provides an innovative and simple way to build beautiful user interfaces (UIs) for all Apple platforms, from iOS and macOS through to watchOS and tvOS, using the Swift programming language. In this recipe-based cookbook, you’ll cover the foundations of SwiftUI as well as the new SwiftUI 3 features introduced in iOS 15 and explore a range of essential techniques and concepts that will help you through the development process. The cookbook begins by explaining how to use basic SwiftUI components. Once you’ve learned the core concepts of UI development, such as Views, Controls, Lists, and ScrollViews, using practical implementations in Swift, you'll advance to adding useful features to SwiftUI using drawings, built-in shapes, animations, and transitions. You’ll understand how to integrate SwiftUI with exciting new components in the Apple development ecosystem, such as Combine for managing events and Core Data for managing app data. Finally, you’ll write iOS, macOS, and watchOS apps by sharing the same SwiftUI codebase. By the end of this SwiftUI book, you'll have discovered a range of simple, direct solutions to common problems encountered when building SwiftUI apps.
Table of Contents (17 chapters)

Chapter 8: Animating with SwiftUI

SwiftUI has introduced not only a new way of describing UI elements and components but also a new way of implementing animations. In the case of animations, an even more complex change of thinking is needed. Though the layout concept is inherently declarative, the animation concept is inherently imperative.

When creating an animation in UIKit, for example, it is normal to describe it as a series of steps: when this happens, do that animation for one second, then another animation for two seconds.

Animation in the SwiftUI way requires us to define three parts:

  • A trigger: An event that happens, such as a button click, a slider, a gesture, and so on
  • A change of data: A change of an @State variable, such as a Boolean flag
  • A change of UI: A change of something that is represented visually following the change of data – for example, a vertical or horizontal offset, or the size of a component that has one value when the flag is...