Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
SwiftUI Essentials – iOS 14 Edition

You're reading from  SwiftUI Essentials – iOS 14 Edition

Product type Book
Published in May 2021
Publisher Packt
ISBN-13 9781801813228
Pages 494 pages
Edition 1st Edition
Languages
Author (1):
Neil Smyth Neil Smyth
Profile icon Neil Smyth

Table of Contents (56) Chapters

1. Start Here 2. Joining the Apple Developer Program 3. Installing Xcode 12 and the iOS 14 SDK 4. An Introduction to Xcode 12 Playgrounds 5. Swift Data Types, Constants and Variables 6. Swift Operators and Expressions 7. Swift Control Flow 8. The Swift Switch Statement 9. Swift Functions, Methods and Closures 10. The Basics of Swift Object-Oriented Programming 11. An Introduction to Swift Subclassing and Extensions 12. An Introduction to Swift Structures and Enumerations 13. An Introduction to Swift Property Wrappers 14. Working with Array and Dictionary Collections in Swift 15. Understanding Error Handling in Swift 5 16. An Overview of SwiftUI 17. Using Xcode in SwiftUI Mode 18. SwiftUI Architecture 19. The Anatomy of a Basic SwiftUI Project 20. Creating Custom Views with SwiftUI 21. SwiftUI Stacks and Frames 22. SwiftUI State Properties, Observable, State and Environment Objects 23. A SwiftUI Example Tutorial 24. SwiftUI Lifecycle Event Modifiers 25. SwiftUI Observable and Environment Objects – A Tutorial 26. SwiftUI Data Persistence using AppStorage and SceneStorage 27. SwiftUI Stack Alignment and Alignment Guides 28. SwiftUI Lists and Navigation 29. A SwiftUI List and Navigation Tutorial 30. An Overview of List, OutlineGroup and DisclosureGroup 31. A SwiftUI List, OutlineGroup and DisclosureGroup Tutorial 32. Building SwiftUI Grids with LazyVGrid and LazyHGrid 33. Building Tabbed and Paged Views in SwiftUI 34. Building Context Menus in SwiftUI 35. Basic SwiftUI Graphics Drawing 36. SwiftUI Animation and Transitions 37. Working with Gesture Recognizers in SwiftUI 38. Creating a Customized SwiftUI ProgressView 39. An Overview of SwiftUI DocumentGroup Scenes 40. A SwiftUI DocumentGroup Tutorial 41. An Introduction to SiriKit 42. A SwiftUI SiriKit Messaging Extension Tutorial 43. Customizing the SiriKit Intent User Interface 44. A SwiftUI SiriKit NSUserActivity Tutorial 45. An Overview of Siri Shortcut App Integration 46. A SwiftUI Siri Shortcut Tutorial 47. Building Widgets with SwiftUI and WidgetKit 48. A SwiftUI WidgetKit Tutorial 49. Supporting WidgetKit Size Families 50. A SwiftUI WidgetKit Deep Link Tutorial 51. Adding Configuration Options to a WidgetKit Widget 52. Integrating UIViews with SwiftUI 53. Integrating UIViewControllers with SwiftUI 54. Integrating SwiftUI with UIKit 55. Preparing and Submitting an iOS 14 Application to the App Store Index

36. SwiftUI Animation and Transitions

This chapter is intended to provide an overview and examples of animating views and implementing transitions within a SwiftUI app. Animation can take a variety of forms including the rotation, scaling and motion of a view on the screen.

Transitions, on the other hand, define how a view will appear as it is added to or removed from a layout, for example whether a view slides into place when it is added, or shrinks from view when it is removed.

36.1 Creating the AnimationDemo Example Project

To try out the examples in this chapter, create a new Multiplatform App Xcode project named AnimationDemo.

36.2 Implicit Animation

Many of the built-in view types included with SwiftUI contain properties that control the appearance of the view such as scale, opacity, color and rotation angle. Properties of this type are animatable, in that the change from one property state to another can be animated instead of occurring instantly. One way to animate these changes to a view is to use the animation() modifier (a concept referred to as implicit animation because the animation is implied for any modifiers applied to the view that precede the animation modifier).

To experience basic animation using this technique, modify the ContentView.swift file in the AnimationDemo project so that it contains a Button view configured to rotate in 60 degree increments each time it is tapped:

struct ContentView : View {

    

    @State private var rotation: Double = 0

 

    var body: some View {

    ...

36.3 Repeating an Animation

By default, an animation will be performed once each time it is initiated. An animation may, however, be configured to repeat one or more times. In the following example, the animation is configured to repeat a specific number of times:

.animation(Animation.linear(duration: 1).repeatCount(10))

Each time an animation repeats, it will perform the animation in reverse as the view returns to its original state. If the view is required to instantly revert to its original appearance before repeating the animation, the autoreverses parameter must be set to false:

.animation(Animation.linear(duration: 1).repeatCount(10,

       autoreverses: false))

An animation may also be configured to repeat indefinitely using the repeatForever() modifier as follows:

.repeatForever(autoreverses: true))

36.4 Explicit Animation

As previously discussed, implicit animation using the animation() modifier implements animation on any of the animatable properties on a view that appear before the animation modifier. SwiftUI provides an alternative approach referred to as explicit animation which is implemented using the withAnimation() closure. When using explicit animation, only the property changes that take place within the withAnimation() closure will be animated. To experience this in action, modify the example so that the rotation effect is performed within a withAnimation() closure and remove the animation() modifier:

var body: some View {

    Button(action: { withAnimation(.linear (duration: 2)) {

            self.rotation =

               (self.rotation < 360 ? self.rotation + 60 : 0)

    ...

36.5 Animation and State Bindings

Animations may also be applied to state property bindings such that any view changes that occur as a result of that state value changing will be animated. If the state of a Toggle view causes one or more other views to become visible to the user, for example, applying an animation to the binding will cause the appearance and disappearance of all those views to be animated.

Within the ContentView.swift file, implement the following layout which consists of a VStack, Toggle view and two Text views. The Toggle view is bound to a state property named visible, the value of which is used to control which of the two Text views is visible at one time:

.

.

@State private var visibility = false

 

var body: some View {

   VStack {

        Toggle(isOn: $visibility) {

           Text("Toggle Text Views")

 ...

36.6 Automatically Starting an Animation

So far in this chapter, all the animations have been triggered by an event such as a button click. Often an animation will need to start without user interaction, for example when a view is first displayed to the user. Since an animation is triggered each time an animatable property of a view changes, this can be used to automatically start an animation when a view appears.

To see this technique in action, modify the example ContentView.swift file as follows:

struct ContentView : View {

    

    var body: some View {

        

        ZStack {

            Circle()

                .stroke(lineWidth: 2)

          ...

36.7 SwiftUI Transitions

A transition occurs in SwiftUI whenever a view is made visible or invisible to the user. To make this process more visually appealing than having the view instantly appear and disappear, SwiftUI allows these transitions to be animated in several ways using either individual effects or by combining multiple effects.

Begin by implementing a simple layout consisting of a Toggle button and a Text view. The toggle is bound to a state property which is then used to control whether the text view is visible. To make the transition more noticeable, animation has been applied to the state property binding:

struct ContentView : View {

 

    @State private var isButtonVisible: Bool = true

 

    var body: some View {

       VStack {

            Toggle(isOn:$isButtonVisible.animation(

   ...

36.8 Combining Transitions

SwiftUI transitions are combined using an instance of AnyTransition together with the combined(with:) method. To combine, for example, movement with opacity, a transition could be configured as follows:

.transition(AnyTransition.opacity.combined(with: .move(edge: .top)))

When the above example is implemented, the Text view will include a fading effect while moving.

To remove clutter from layout bodies and to promote re-usability, transitions can be implemented as extensions to the AnyTransition class. The above combined transition, for example, can be implemented as follows:

extension AnyTransition {

    static var fadeAndMove: AnyTransition {

        AnyTransition.opacity.combined(with: .move(edge: .top))

    }

}

When implemented as an extension, the transition can simply be passed as an argument to the transition() modifier, for example:

.transition...

36.9 Asymmetrical Transitions

By default, SwiftUI will simply reverse the specified insertion transition when removing a view. To specify a different transition for adding and removing views, the transition can be declared as being asymmetric. The following transition, for example, uses the scale transition for view insertion and sliding for removal:

.transition(.asymmetric(insertion: .scale, removal: .slide))

36.10 Summary

This chapter has explored the implementation of animation when changes are made to the appearance of a view. In the case of implicit animation, changes to a view caused by modifiers can be animated through the application of the animated() modifier. Explicit animation allows only specified properties of a view to be animated in response to appearance changes. Animation may also be applied to state property bindings such that any view changes that occur as a result of that state value changing will be animated.

A transition occurs when a view is inserted into, or removed from, a layout. SwiftUI provides several options for animating these transitions including fading, scaling and sliding. SwiftUI also provides the ability to both combine transitions and define asymmetric transitions where different animation effects are used for insertion and removal of a view.

lock icon The rest of the chapter is locked
You have been reading a chapter from
SwiftUI Essentials – iOS 14 Edition
Published in: May 2021 Publisher: Packt ISBN-13: 9781801813228
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime}