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 a Text 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:

  1. Enhance your UI animations and transitions: This session covers how to use SwiftUI animation types to animate UIKit and AppKit views, including custom animations.
  2. SwiftUI essentials: This session provides a deep dive into the fundamentals of views and animations in SwiftUI.
  3. 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.