Create an animated button in swift ui
Asked on 07/30/2024
1 search
To create an animated button in SwiftUI, you can leverage the powerful animation capabilities provided by the framework. Here’s a basic example to get you started:
import SwiftUI
struct AnimatedButton: View {
@State private var isPressed = false
var body: some View {
Button(action: {
withAnimation(.spring()) {
isPressed.toggle()
}
}) {
Text("Press Me")
.padding()
.background(isPressed ? Color.blue : Color.green)
.foregroundColor(.white)
.clipShape(Capsule())
.scaleEffect(isPressed ? 1.2 : 1.0)
}
}
}
struct ContentView: View {
var body: some View {
AnimatedButton()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
In this example:
- A
Button
is created with aText
label. - The button's background color and scale change when it is pressed.
- The
withAnimation
function is used to animate the changes with a spring animation.
For more advanced animations and effects, you can refer to the sessions from WWDC:
- Enhance your UI animations and transitions: This session covers how to use SwiftUI animation types to animate UIKit and AppKit views, including custom animations.
- SwiftUI essentials: This session provides a deep dive into the fundamentals of views and animations in SwiftUI.
- Create custom hover effects in visionOS: This session discusses creating custom hover effects and animating them with SwiftUI.
These sessions will provide you with a comprehensive understanding of how to create and customize animations in SwiftUI.

Enhance your UI animations and transitions
Explore how to adopt the zoom transition in navigation and presentations to increase the sense of continuity in your app, and learn how to animate UIKit views with SwiftUI animations to make it easier to build animations that feel continuous.

SwiftUI essentials
Join us on a tour of SwiftUI, Apple’s declarative user interface framework. Learn essential concepts for building apps in SwiftUI, like views, state variables, and layout. Discover the breadth of APIs for building fully featured experiences and crafting unique custom components. Whether you’re brand new to SwiftUI or an experienced developer, you’ll learn how to take advantage of what SwiftUI has to offer when building great apps.

What’s new in AppKit
Discover the latest advances in Mac app development. Get an overview of the new features in macOS Sequoia, and how to adopt them in your app. Explore new ways to integrate your existing code with SwiftUI. Learn about the improvements made to numerous AppKit controls, like toolbars, menus, text input, and more.