Animating SwiftUI Applications - Stephen DeStefano - E-Book

Animating SwiftUI Applications E-Book

Stephen DeStefano

0,0
33,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Unleash the power of SwiftUI 4 by building dynamic, cross-platform projects with iOS 16 that will amaze your users

Purchase of the print or Kindle book includes a free PDF eBook

Key Features

  • Explore the basics of declarative programming and animation
  • Understand the fundamentals of SwiftUI and animatable properties
  • Learn while working on beginner-to-advanced level animation projects

Book Description

Swift and SwiftUI are the backbone of Apple application development, making them a crucial skill set to learn. Animating SwiftUI Applications focuses on the creation of stunning animations, making you proficient in this declarative language and employing a minimal code approach.



In this book, you'll start by exploring the fundamentals of SwiftUI and animation, before jumping into various projects that will cement these skills in practice. You will explore some simple projects, like animating circles, creating color spectrums with hueRotation, animating individual parts of an image, as well as combining multiple views together to produce dynamic creations. The book will then transition into more advanced animation projects that employ the GeometryReader, which helps align your animations across different devices, as well as creating word and color games. Finally, you will learn how to integrate the SpriteKit framework into our SwiftUI code to create scenes with wind, fire, rain, and or snow scene, along with adding physics, gravity, collisions, and particle emitters to your animations.



By the end of this book, you’ll have created a number of different animation projects, and will have gained a deep understanding of SwiftUI that can be used for your own creations.

What you will learn

  • Understand the fundamentals of SwiftUI and declarative programming
  • Master animation concepts like state variables and time curves
  • Explore animation properties like hueRotation, opacity, and scale
  • Create animations using physics, gravity, collision, and more
  • Use the GeometryReader to align views across various platformsCombine different animations for more dynamic effects
  • Add audio to your animations for an interactive experience

Who this book is for

This book is for aspiring SwiftUI developers who have a basic understanding of Swift. It can also be used by SwiftUI developers, UIKit developers, and iOS developers that are new to SwiftUI and want to improve their animation proficiency.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 521

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Animating SwiftUI Applications

Create visually stunning and engaging animations for iOS with SwiftUI

Stephen DeStefano

BIRMINGHAM—MUMBAI

Animating SwiftUI Applications

Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Rohit Rajkumar

Publishing Product Manager: Nitin Nainani

Senior Editor: Hayden Edwards

Technical Editor: Joseph Aloocaran

Copy Editor: Safis Editing

Project Coordinator: Aishwarya Mohan

Proofreader: Safis Editing

Indexer: Rekha Nair

Production Designer: Nilesh Mohite

Marketing Coordinator: Nivedita Pandey

First published: March 2023

Production reference: 1100323

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80323-266-9

www.packtpub.com

To my family, who have always been my source of love, support, and encouragement. Your unwavering belief in me has been my foundation, and I am eternally grateful for everything you have done for me. This book is dedicated to each and every one of you with heartfelt love and gratitude.

And to my best friend, Akiko, who has been my faithful companion on our life journey together. Thank you for your love, support, and endless laughter.

With love and admiration,

Stephen DeStefano

Foreword

SwiftUI has come a long way since it was first introduced in 2019. At first, the framework was nothing more than a novelty, but it has grown significantly over the past few years. The tools have been improved and all the bugs have been fixed, but perhaps the most important aspect of this evolution is that the framework is now forging its own path, introducing tools that didn’t exist before, such as widgets and charts, and integrating old technologies in a way that makes it easy for developers to build professional applications. Performing complex tasks such as file and database management, or adding personal touches that set your application apart, is now easier than ever.

However, nothing represents these innovations better than animation, giving the user interface a professional look that cannot be achieved with static elements. Creating an animation with previous frameworks required dozens of lines of code and setting multiple parameters. SwiftUI has always included built-in support for animation, but the feature has now been enhanced and extended to allow developers to create stunning user interfaces with ease.

In this book, Stephen DeStefano shows you how to create SwiftUI animations and how to implement them to achieve the look and feel you have always wanted for your application. With clear and easy-to-follow examples, Stephen explains all the aspects of the technology, from animating simple views to creating complex animations for custom graphics, allowing you to focus on your project and get results fast.

J.D. Gauchat

Author of SwiftUI for Masterminds

Contributors

About the author

Stephen DeStefano is a seasoned SwiftUI programmer with over a decade of experience in teaching beginners the fundamentals of Apple’s Swift language. His passion for programming, specifically SwiftUI and animations, is evident in his work, including several in-depth and comprehensive courses featured on Udemy and other platforms.

Throughout his career, he’s had the privilege of working with some of the leading Swift and SwiftUI programmers in the field, including Paul Hudson and J.D. Gauchat, but his own unique approach of blending best practices and industry standards with hands-on tutorials and exercises has attracted over 30,000 students, solidifying him as a sought-after SwiftUI educator.

About the reviewers

Nimesh Neema is a passionate programmer who loves well-designed software. He is proficient with Apple developer technologies and has written apps for iPhone, iPad, Mac, Apple Watch, and Apple TV. He has an excellent understanding of shell scripting, version control, and software engineering principles.

In his career spanning over 15 years, he has worked with teams of diverse sizes and backgrounds and has experience writing utility, payment, gaming, hospitality, and low-level system apps.

He runs a software engineering consultancy, Perspicacious Solutions Private Limited, with clients from around the world. He takes up corporate training and speaking gigs and is one of the highly rated Apple development experts on Codementor.io.

Scotti Dscyre is a highly accomplished and dedicated iOS developer with strong experience in developing and maintaining large-scale applications at the production level. He possesses in-depth knowledge of the iOS ecosystem and his expertise embraces a wide range of technologies and tools, including Swift, Objective-C, UIKit, SwiftUI, Swift Concurrency, Combine, RxSwift, CoreData, CoreAnimation, XCTest, MVVM, clean architecture, composable architecture, the Swift Package Manager, CocoaPods, fastlane, Git, and Bitrise.

He is also devoted to open source contributions and has distributed a number of open source packages, including ShuffleIt and SwiftTheming on GitHub.

Table of Contents

Preface

1

Exploring the Fundamentals of SwiftUI

Technical requirements

Understanding imperative and declarative programming

Exploring the Xcode interface

Understanding the state

Understanding SwiftUI structures

Computed properties

Stacks

Spacer views

Divider views

The padding modifier

Closures

GeometryReader

Summary

2

Understanding Animation with SwiftUI

Technical requirements

What is animation?

Understanding timing curves

Understanding animation types

Triggering animations

Exploring animatable properties

The offset property

Hue rotation

Opacity

Scale

Stroke, trim, and corner radius

Summary

3

Creating a Breathing App

Technical requirements

Setting up the project with Xcode

Adding the variables

Implementing a background color

Adding the circles

Adding the first pair of circles

Adding the second pair of circles

Adding the third pair of circles

Animating the circles

Summary

4

Building a Record Player

Technical requirements

Adding images to the Assets catalog

Creating the record player elements

Creating the record player box

Creating the spinning record

Creating the record player arm

Adding a custom dynamic button

Creating a sound file to play audio

Combining all the elements into one view

Testing the project

Summary

5

Animating Colorful Kaleidoscope Effects

Technical requirements

Adding the Binding variable and images

Adding a Picker control and using a ForEach view

Adding the variables and background color

Adding the Image view and using the hueRotation modifier

Summary

6

Animating a Girl on a Swing

Technical requirements

Gathering and slicing images

Adding the animating variables

Adding the images to the scene

Adding the background

Adding the right leg

Adding the girl

Adding the left leg

Bringing the images together

Using the mask modifier

Summary

7

Building a Series of Belts and Gears

Technical requirements

Animating our first circular gear

Animating a worm gear using shadows

Using a marching ants effect to create a gear belt

Animating a gear shaft image

Animating a fan image

Bringing everything together in ContentView

Adding the motor

Adding the gears along the x-, y-, and z-axes

Adding the worm gear

Adding the belts

Adding the gear shafts

Adding the fan

Adding the background

Summary

8

Animating a Bouquet of Flowers

Technical requirements

Adding the variables and a winter background

Animating the text labels

Using the blur modifier to create a vapor effect

Animating flower petals in an arc

Adding the flower bouquet and the animated breath

Creating falling snow in the scene

Adding the UIViewRepresentable protocol

Dealing with methods and errors

Adding the CAEmitter class

Summary

9

Animating Strokes around Shapes

Technical requirements

Converting images into Swift code

Removing the image backgrounds

Vectorizing the images

Translating the SVG file into Swift code

Animating images with the stroke modifier

Creating a stroke animation on the “WE” image

Creating a stroke animation on the heart image

Creating a stroke animation on the SwiftUI logo image

Combining the animated strokes

Summary

10

Creating an Ocean Scene

Technical requirements

Adding the wave’s offset property

Creating a wave shape using the Shape protocol and Path function

Adding the wave’s animatableData property

Setting up the ContentView for animation

Duplicating and animating the wave shape in the ContentView

Adding an animated floating buoy to the ocean scene

Making the buoy light blink

Making the buoy move

Adding the buoy to the scene

Adding sound effects

Summary

11

Animating an Elevator

Technical requirements

Setting up the project and adding a Binding variable

Assembling the elevator using images and the GeometryReader view

Putting people inside the elevator

Creating a data model and using the ObservableObject protocol

Adding the data model functions

Adding the doorOpenTimer function

Adding the playChimeSound function

Adding the playDoorOpenCloseSound function

Adding the floorNumbers function

Adding the stopTimer function

Adding the background, a button, and animating the doors

Adding floor indicator lights

Summary

12

Creating a Word Game (Part 1)

Technical requirements

Setting up the project and creating a data model

Building out the UI by adding a text field and list

Displaying a character count next to each word in the list

Checking the entered words for duplicates

Adding a random word with a button press

Checking if the user’s entered word is possible

Checking whether the user’s entered word is a real word

Creating HeaderView with an info button

Creating PickerView

Adding PickerView

Styling PickerView

Summary

13

Creating a Word Game (Part 2)

Technical requirements

Creating a settings screen

Adding the language buttons

Adding a checkmark

Adding a dismiss button

Styling the UI

Adding the background

Adding animations to the game word

Implementing user feedback with alerts

Adding a Footer View to display more information

Adding haptics and button sounds

Summary

14

Creating a Color Game

Technical requirements

Understanding colors

Creating the Title view

Creating the target and guess circles

Creating the Picker view

Creating the target and guess rectangles

Making the color sliders

Keeping track of the user’s score with a button

Showing the user’s score in an Alert view

Resetting the game

Adding a background

Adding confetti using Swift packages

Summary

15

Integrating SpriteKit into Your SwiftUI Projects

Technical requirements

Animating pipe smoke

Creating a SpriteKit particle file

Integrating the Smoke file into a SwiftUI View

Animating coffee steam

Creating the Smoke SpriteKit particle file

Creating the Coffee Steam struct

Filling out ContentView

Animating rocket fire

Adding FireView

Adding RocketView

Putting things together inside ContentView

Animating a blizzard

Creating two Snow SpriteKit particle files

Creating a view that combines the two SKS files

Animating the tree branches

Animating rain

Creating the Rain SpriteKit particle file

Creating the raindrops

Creating the puddle

Putting it all together

Animating a magic wand

Creating the magic SpriteKit particle file

Summary

Index

Other Books You May Enjoy

Preface

Welcome to Animating SwiftUI Applications, a book designed to help you create engaging and interactive user experiences using SwiftUI animations.

SwiftUI is a modern, declarative, and intuitive framework for building user interfaces on Apple platforms, and it comes with a powerful and easy-to-use animation system that lets you add motion and life to your apps effortlessly.

With SwiftUI animations, you can add dynamic transitions, smooth movements, and delightful effects to your app’s UI elements, making them more engaging and intuitive for users. You can animate anything from simple buttons and text fields to complex layouts and custom shapes, all with just a few lines of code.

In this book, you will learn how to use SwiftUI animations to create various types of effects, including transitions, gestures, and even SpriteKit animations. You’ll explore different animation techniques, such as implicit, explicit, and combined animations, and learn how to apply them to create stunning and responsive user interfaces. By the end of the book, you’ll be able to create beautiful and engaging animations and apps that really stand out from the crowd.

Who this book is for

This book is aimed at those who have a basic working knowledge of Swift but are a beginner when it comes to SwiftUI. The book starts with some basics of the SwiftUI framework, and then proceeds with simple animation examples, before moving on to more advanced topics.

What this book covers

In Chapter 1, Exploring the Fundamentals of SwiftUI, you will receive a comprehensive overview of the two distinct programming styles: imperative and declarative. Then, we will delve into the Xcode interface, the free application provided by Apple, where all our development work will take place. Finally, we will examine the fundamental SwiftUI structures required for creating applications, laying the groundwork for advancing with animations.

In Chapter 2, Understanding Animation in SwiftUI, we will examine the mechanics of animations, covering essential topics such as timing curves and animatable properties. This will establish a solid foundation for the projects we will construct.

In Chapter 3, Creating a Breathing App, we will harness the power of SwiftUI’s user-friendly modifiers and design tools to effortlessly rotate, scale, and move views. Moreover, we will utilize the animation modifier to smoothly interpolate between start and end values, producing a seamless animation.

In Chapter 4, Building a Record Player, we will incorporate images from the Asset Catalog into our code. Then, we will create standalone files for creating various views that can be seamlessly integrated into the main view for display. Furthermore, we will add a button to trigger the animation and incorporate sound into the project.

In Chapter 5, Animating Colorful Kaleidoscope Effects, we will explore the animation of colors using the hueRotation modifier, where hue pertains to the colors of the object and rotation signifies the rotation or animation of these colors. We will construct a straightforward project that showcases various images, and then utilize hueRotation to alter the color of the images, producing a kaleidoscope-like effect.

In Chapter 6, Animating a Girl on a Swing, we will investigate the process of cutting up images into separate parts, and then using code to animate these separate parts together in creative and unique ways. Additionally, we will utilize a new modifier, mask, to help disguise and hide specific areas of our animation that we don’t want to see.

In Chapter 7, Building a Series of Belts and Gears, we will generate a “marching ants” effect by employing the stroke modifier, and then examine how to neatly organize code using Pragma Marks and Groups. We will also animate objects along all three axes, x, y, and z, by utilizing the rotation3Deffect modifier.

In Chapter 8, Animating a Flower, we will construct the illusion of a bouquet of flowers breathing through the use of modifiers such as blur, scale, and rotationEffect. Additionally, we will examine the UIViewRepresentable protocol and the CAEmitter class to incorporate falling snow into the scene.

In Chapter 9, Animating Strokes around Shapes, we will delve into the process of converting bitmap images into vector files, and then transform these vector files into code that we can utilize in a SwiftUI project. Furthermore, we will animate a stroke around various shapes through the use of the stroke modifier and timers.

In Chapter 10, Creating an Ocean Scene, we will utilize the Shape protocol to craft an oceanic scene featuring undulating waves, a buoy that bobs in the water, a flashing light, and accompanying sounds.

In Chapter 11, Animating an Elevator, we will employ GeometryReader and the proxy constant to insert images into the project and position them appropriately. This will enable the images to be dynamically resized based on the device in use. Furthermore, we will create a DataModel to store the app’s data and functions and make use of timers to activate doors and light animations at various points in the scene.

In Chapter 12, Creating a Word Game – Part 1, we will commence with the construction of a word-based game that allows players to input words to play using three different languages, with validations in place to verify their choices.

In Chapter 13, Creating a Word Game – Part 2, we will add the finishing touches to our word game by organizing its properties and functions within DataModel and creating distinct header and footer views to display information to the user. Additionally, we will incorporate user feedback in three different forms: pop-up alerts, haptic feedback, and audio.

In Chapter 14, Creating a Color Game, we will develop an RGB color-matching game that keeps track of the score and displays a celebratory confetti animation upon the player achieving a perfect score. We will also examine the integration of Swift packages into the project.

In Chapter 15, Integrating SpriteKit into your SwiftUI Projects, we will create six separate projects that showcase SpriteKit and a variety of particle systems. We will learn how to blend realistic and fluid animations seamlessly with your SwiftUI code.

To get the most out of this book

To get the most out of this book, a working knowledge of the Swift programming language is required. Knowledge of the fundamentals of SwiftUI is helpful, but not required.

You will also need a Mac computer and have downloaded the free software, Xcode (Xcode runs well on most versions of macOS, so it should work with the version you have).

We will build our projects for iOS devices.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

If you prefer to learn through video tutorials, I recommend my Swift and SwiftUI courses over at udemy.com. Other highly recommended resources that can help to build your coding skills fast are Paul Hudson’s works at hackingwithswift.com, and J.D. Gauchat’s SwiftUI for Masterminds book.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Animating-SwiftUI-Applications. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://packt.link/O1ZYe.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “He is very thorough as well, and you can find his work at jdgauchat.com.”

A block of code is set as follows:

struct ContentView: View {     var body: some View {         HStack {             Text(“Hello”)             Spacer()

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

struct ContentView: View {    var body: some View {        VStack(alignment: .leading)  {       Text(“Hi, I’m child one in this vertical stack”)       Text(“Hi, I’m child two in this vertical stack”)

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “We will be using the first option, which is Create a new Xcode project, for all of our projects, so select that.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read Animating SwiftUI Applications, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781803232669

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly