DEV Community

Anis Ali Khan
Anis Ali Khan

Posted on

Tutorial 23: Working with Animations and Transitions in UIKit and SwiftUI πŸŽ¬πŸš€

Table of Contents πŸ“–

  1. Introduction 🎀

    • What are animations and transitions?
    • Why use animations in iOS apps?
    • UIKit vs. SwiftUI animations
  2. UIKit Animations πŸ“²

    • UIView animations: UIView.animate(withDuration:)
    • Spring animations: UIViewPropertyAnimator
    • Transition animations: UIView.transition(with:)
  3. SwiftUI Animations πŸ’‘

    • Implicit animations: .animation() modifier
    • Explicit animations: withAnimation {}
    • Transitions: .transition(.scale) and .transition(.slide)
  4. Using iPhone Sensors with CoreMotion πŸ“‘

    • What is CoreMotion?
    • Accessing the accelerometer
    • Using motion data to animate UI elements
  5. Building the Floating Ball App πŸ€πŸ’¨

    • Project setup
    • Creating the UI (ball and background)
    • Implementing animations
    • Reading motion sensor data
    • Combining motion data with animations
  6. Conclusion πŸŽ‰

    • Recap of key learnings
    • Next steps and further improvements

1. Introduction 🎀

Animations make apps feel alive! Smooth transitions and interactions help users feel engaged.

UIKit and SwiftUI both offer powerful animation tools:

  • UIKit: Gives full control over animations, useful for custom transitions.
  • SwiftUI: Provides a declarative way to add fluid animations with minimal code.

In this tutorial, we will learn both approaches and combine them in an exciting Floating Ball App that reacts to iPhone tilts using motion sensors! πŸ“‘πŸ“±


2. UIKit Animations πŸ“²

Simple UIView Animation πŸƒβ€β™‚οΈπŸ’¨

UIView.animate(withDuration: 1.0) {
    self.view.alpha = 0.5  // Fade effect
}
Enter fullscreen mode Exit fullscreen mode

Spring Animation 🦘

UIView.animate(withDuration: 1.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1) {
    self.view.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
}
Enter fullscreen mode Exit fullscreen mode

Transition Animation πŸ”„

UIView.transition(with: someView, duration: 0.5, options: .transitionFlipFromLeft, animations: {
    someView.isHidden.toggle()
})
Enter fullscreen mode Exit fullscreen mode

3. SwiftUI Animations πŸ’‘

Implicit Animation ✨

struct AnimatedView: View {
    @State private var isScaled = false

    var body: some View {
        Circle()
            .frame(width: 100, height: 100)
            .scaleEffect(isScaled ? 1.5 : 1.0)
            .animation(.easeInOut(duration: 1.0), value: isScaled)
            .onTapGesture { isScaled.toggle() }
    }
}
Enter fullscreen mode Exit fullscreen mode

Explicit Animation 🎭

struct ExplicitAnimationView: View {
    @State private var position = CGSize.zero

    var body: some View {
        Circle()
            .frame(width: 100, height: 100)
            .offset(position)
            .gesture(
                DragGesture()
                    .onChanged { position = $0.translation }
                    .onEnded { _ in 
                        withAnimation(.spring()) {
                            position = .zero
                        }
                    }
            )
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Using iPhone Sensors with CoreMotion πŸ“‘

CoreMotion gives access to accelerometer and gyroscope data, allowing us to make interactive UIs based on motion.

Setting Up MotionManager πŸ‹οΈβ€β™‚οΈ

import CoreMotion

class MotionManager: ObservableObject {
    private var motion = CMMotionManager()
    @Published var xTilt: Double = 0
    @Published var yTilt: Double = 0

    init() {
        startMotionUpdates()
    }

    func startMotionUpdates() {
        if motion.isAccelerometerAvailable {
            motion.accelerometerUpdateInterval = 0.1
            motion.startAccelerometerUpdates(to: .main) { data, error in
                if let data = data {
                    self.xTilt = data.acceleration.x
                    self.yTilt = data.acceleration.y
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

5. Building the Floating Ball App πŸ€πŸ’¨

Step 1: Create a New SwiftUI Project πŸ“‚

  1. Open Xcode and create a new SwiftUI app.
  2. Name it FloatingBall.

Step 2: Create the UI 🎨

struct FloatingBallView: View {
    @ObservedObject var motion = MotionManager()

    var body: some View {
        ZStack {
            Color.black.edgesIgnoringSafeArea(.all)

            Circle()
                .fill(Color.green)
                .frame(width: 80, height: 80)
                .offset(x: motion.xTilt * 100, y: -motion.yTilt * 100)
                .animation(.easeInOut(duration: 0.3), value: motion.xTilt)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Run the App and Tilt Your Phone! πŸ“±

You’ll see the ball move smoothly in response to your tilts! πŸš€


6. Conclusion πŸŽ‰

  • UIKit is great for fine-tuned control over animations.
  • SwiftUI makes it easy to animate elements declaratively.
  • CoreMotion allows us to use iPhone sensors for interactive UI experiences.

Next Steps:

  • Try adding a parallax background effect!
  • Implement haptic feedback for a richer experience.

This concludes our tutorial! Hope you enjoyed building the Floating Ball app. πŸŽ₯✨

Happy coding! πŸš€

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere β€œthank you” often brightens someone’s dayβ€”share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay