Mastering SwiftUI: Building Beautiful and Interactive User Interfaces: Part 4

Modabbir Tarique
9 min readAug 19, 2023

--

SwiftUI Animation: Elevate Your UI with Dynamic Delights

Hola! Welcome to our comprehensive guide to SwiftUI, Apple’s declarative UI framework for building delightful and interactive user interfaces on iOS, macOS, watchOS, and tvOS. In this article, we will embark on an exciting journey into the world of SwiftUI, exploring its core concepts, advantages, and lifecycle.

In the first part of our exploration, we will delve into the fundamental aspects of SwiftUI. If you missed it, don’t worry — you can catch up right here!

As we progress to the second part, we will focus on building strong foundations in layout design. In case if you missed that, don’t worry — you can read it from here!

In the previous part of our journey, we’ve delved into the foundations of SwiftUI, exploring Scroll View, Dynamic List View, Complex Lists with dynamic and static elements, Hierarchical List, Customizing lists using different styling options, and the fascinating world of SwiftUI Gestures. We’ve built a solid understanding of SwiftUI’s capabilities, empowering us to create versatile and interactive user interfaces.

Now, it’s time to take our skills to the next level as we venture into the captivating realm of SwiftUI animations. Animation, often referred to as the heartbeat of user interfaces, breathes life into our apps, engaging users and providing a delightful experience. With SwiftUI’s ingenious animation tools, we’re ready to bring our designs to life and create UIs that go beyond static elements.

Topics that we are going to discuss in today’s blog:

  1. Introduction to SwiftUI Animation
  2. Advantages of SwiftUI Animation
  3. Key terminologies
  4. Types of SwiftUI Animation
  5. Moving Circle Animation

Introduction to SwiftUI Animation

Animation isn’t just about making things move; it’s about telling a story through motion. SwiftUI, Apple’s modern UI framework, revolutionizes animation with its declarative syntax and seamless integration into your app’s structure. By leveraging animations, you can captivate users, guide their attention, and provide intuitive feedback.

Advantages of SwiftUI Animation

1. Declarative Syntax: SwiftUI’s animation system follows the same declarative approach as the rest of the framework. We can describe how the animation should look, and SwiftUI takes care of the underlying details. This makes animations more intuitive and easier to reason about.

2. Integration with Views: SwiftUI integrates animation seamlessly with views. Animation modifiers can be applied directly to view properties, keeping the animation code close to the view it affects. This integration simplifies the process of animating changes in our user interface.

3. Implicit Animations: SwiftUI also introduces the concept of implicit animations. Any change to animatable properties within an animation block is automatically animated, eliminating the need for explicit setup. This leads to cleaner and more concise code.

4. Fluid User Experience: Animations provide feedback to users, indicating changes or interactions within the app. SwiftUI animations makes things smoother, make more intuitive user experience, and also enhance the overall usability of our application.

5. Interactive and Responsive: SwiftUI allows you to combine gestures with animations, creating interactive and dynamic user interfaces. This opens the door to building apps that respond to user input in real time, making the app feel alive and engaging.

6. Ease of Use: Creating animations in SwiftUI requires fewer lines of code compared to traditional methods. Animation modifiers are simple to use, enabling developers of all skill levels to add motion to their apps without a steep learning curve.

7. Consistency Across Platforms: SwiftUI animations work seamlessly across all Apple platforms (iOS, macOS, watchOS, tvOS). This consistent behavior allows you to create a unified user experience across various devices.

8. Performance and Optimization: SwiftUI employs underlying optimization techniques to ensure that animations run efficiently. Animations are rendered with optimal performance, resulting in smoother transitions and improved app responsiveness.

9. Prototyping and Experimentation: SwiftUI’s easy-to-use animation system encourages developers to experiment with different animations quickly. This is particularly valuable during the prototyping phase, allowing you to iterate and fine-tune animations easily.

10. Future-Proofing: SwiftUI is Apple’s vision for the future of UI development across their platforms. By learning SwiftUI animations, you’re investing in a skillset that will remain relevant and valuable as the framework evolves.

In summary, SwiftUI animations offer a modern, intuitive, and integrated way to add motion and interactivity to our user interfaces. The advantages of SwiftUI animations extend beyond aesthetics, contributing to a better user experience, enhanced app engagement, and efficient development.

Key terminologies

Here are some key terms you should be familiar with:

  1. Animatable: This is a protocol that types can conform to in SwiftUI. It allows you to create custom animations by defining how a property should be interpolated between its start and end values.
  2. Animation: Describes how a view property changes over time. SwiftUI provides a variety of built-in animations like .easeInOut, .linear, and more. You can also create custom animations using the Animation type.
  3. Animation Modifier: These are methods you apply to a view to animate changes to its properties. For example, .animation(_:) is a modifier that specifies the animation for a view.
  4. Spring Animation: A type of animation that creates a spring-like effect, where the view overshoots its final value before settling.
  5. Ease-In-Out Animation: An animation timing curve where the motion starts slowly, accelerates in the middle of the animation, and then slows down again towards the end.
  6. Binding: A two-way connection between a source of data and a user interface element. It allows changes in one to be automatically reflected in the other.
  7. State: A property wrapper that allows a value to be stored and observed for changes. When a @State property changes, SwiftUI automatically updates the associated views.
  8. @StateObject: A property wrapper for objects that are external to your view but should still trigger view updates when they change.
  9. @ObservedObject: A property wrapper for objects that are external to your view and only need to be observed for changes.
  10. withAnimation: A function you can wrap around code to animate any changes that occur inside it. It automatically applies the specified animation to the changes.
  11. Gesture: In the context of animations, gestures are actions like tapping, dragging, or pinching on the screen that can trigger animations.
  12. UIViewRepresentable: A protocol that allows you to wrap UIKit components in SwiftUI views. This is useful when you need to use UIKit animations or components that are not yet available in SwiftUI.
  13. Interpolator: An object responsible for determining intermediate values between the start and end values of an animatable property.
  14. Modifier Order: The order in which you apply modifiers can affect the appearance and animation of a view. For example, applying a scale modifier before or after an animation modifier can yield different results.
  15. Implicit Animation: When you change a @State property within an animation block, SwiftUI automatically animates the change if it's applied to an animatable property of a view.

These terminologies provide a foundation for working with SwiftUI animations. As you delve deeper into SwiftUI and animation concepts, we’ll gain a better understanding of how these terms interact to create smooth and interactive user interfaces.

Types of SwiftUI Animation

SwiftUI provides various types of animation to help you create dynamic and engaging user interfaces.

Implicit Animation: Implicit animations are the simplest way to animate changes to views in SwiftUI. When we modify a @State property within an animation block, SwiftUI automatically animates the change using the animation settings applied to the view.

withAnimation {
self.scale = 2.0
}

Explicit Animation: Explicit animations give you more control over animations. You can create animations explicitly using the Animation type and apply them to specific view modifiers. This is useful when you want to animate multiple properties with different animations simultaneously.

Animation.easeInOut(duration: 0.5)

Spring Animation: Spring animations create a bouncy effect similar to a physical spring. You can apply spring animations to views using the .spring() modifier.

.scaleEffect(scale)
.animation(.spring())

Transition Animation: Transition animations are used to animate the insertion or removal of views in a layout. They can be applied to view changes inside a NavigationView, a List, or any other container view.

.transition(.slide)

Custom Animations: SwiftUI provides the Animatable protocol that you can adopt to create your own custom animations. This allows you to animate any property that conforms to the Animatable protocol.

View Transition: This type of animation involves transitioning between different views or screens. SwiftUI provides mechanisms for transitioning between views using NavigationLink, TabView, and custom transitions.

GeometryEffect Animation: SwiftUI allows you to create animations based on the geometry of the view. You can use modifiers like .rotationEffect, .offset, and .scaleEffect to animate views based on their position, rotation, and scale.

Particle Animations: SwiftUI allows you to create particle animations using the ParticleEmitter view introduced in iOS 15. This enables you to create effects like confetti, fire, smoke, and more.

These are some of the main types of animations available in SwiftUI. Depending on the project’s needs, we can use a combination of these animation techniques to create visually appealing and interactive user interfaces.

Moving Circle Animation

let’s create a project where we animate a circle’s movement using SwiftUI. In this example, we’ll make a circle move horizontally across the screen.

import SwiftUI

struct ContentView: View {
@State private var circlePosition: CGFloat = 0

var body: some View {
ZStack {
Color.white

Circle()
.foregroundColor(.blue)
.frame(width: 50, height: 50)
.offset(x: circlePosition, y: 0)
.animation(.linear(duration: 2).repeatForever(autoreverses: false))
}
.onAppear() {
self.circlePosition = UIScreen.main.bounds.width - 75
}
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

What we did here:

  • We use the @State property circlePosition to control the circle's horizontal position.
  • The circle’s position is animated using the .animation() modifier. We use the .linear timing curve and set the duration to 2 seconds. The .repeatForever(autoreverses:) modifier creates a continuous animation loop.
  • The onAppear modifier sets the initial position of the circle when the view appears.

Lets see what we achieve here

In this blog post, we embarked on an exciting journey into the world of SwiftUI animations, unraveling the magic behind captivating user experiences. We began by delving into the fundamental concept of animations, understanding how they infuse life into digital interfaces, fostering engagement and delighting users. The advantages of animations were revealed to be not only aesthetic enhancements but also potent tools for conveying information, guiding user interactions, and creating memorable moments.

As we traversed further, we navigated through key terminologies intrinsic to the realm of SwiftUI animations. These terms, such as “Animatable,” “Implicit Animation,” and “Gesture-based Animation,” became our compass, guiding us through the intricacies of animation creation.

Diving deeper into the ocean of possibilities, we explored the varied types of animations that SwiftUI has to offer. From the elegance of implicit animations to the dynamic gestures that beckon user participation, each type unveiled a unique facet of animation’s impact on the user experience. Armed with this knowledge, we equipped ourselves to select the perfect animation type for every scenario, ensuring seamless and fluid interactions.

With our understanding solidified, we rolled up our sleeves and embarked on a hands-on journey. We embarked on the creation of a moving circle animation — a simple yet impactful project that encapsulated the essence of SwiftUI animations. By animating the circle’s movement, we unearthed the power of state management and animation modifiers in crafting engaging visual narratives.

As we draw the curtains on this part of our exploration, the path ahead beckons with even greater promise. In the upcoming segments of this series, we will embark on a series of exciting projects that harness the full potential of SwiftUI animations. These projects will not only reinforce our understanding but also empower us to create animations that resonate with users on a profound level.

So, dear readers, prepare yourselves to take your SwiftUI animation journey to new heights. From dynamic user interactions to mesmerizing visual choreography, each project will unravel a new layer of creativity and technical prowess. As we embrace the boundless world of SwiftUI animations together, let’s remember that each animation tells a story — a story that captivates, communicates, and leaves an indelible mark on the digital canvas.

Stay tuned for the upcoming chapters, where we’ll breathe life into our interfaces and unlock the true artistry of SwiftUI animations.

Thank you for joining me on this SwiftUI journey. Happy coding, and let’s have fun building amazing apps with SwiftUI!

Feel free to connect me on LinkedIn

--

--

Modabbir Tarique

Full time Software Developer | IIT Guwahati Graduate | Tech Enthusiast