Tap animation on Image SwiftUI

Viewed 3406

How can I make an animation on an image so when I tap it and hold it scales backwards and when I release it the image return to its original size?

struct ContentView: View {
    var body: some View {
        Image(systemName: "heart")
        .onTapGesture {
        // Gesture when held down and released
        }
    }
}
1 Answers

Here is a demo of possible solution. Tested with Xcode 12 / iOS 14.

demo

struct DemoImageScale: View {
    @GestureState private var isDetectingPress = false

    var body: some View {
        Image("plant")
            .resizable().aspectRatio(contentMode: .fit)
            .scaleEffect(isDetectingPress ? 0.5 : 1)
            .animation(.spring())
            .gesture(LongPressGesture(minimumDuration: 0.1).sequenced(before:DragGesture(minimumDistance: 0))
                .updating($isDetectingPress) { value, state, _ in
                    switch value {
                        case .second(true, nil):
                            state = true
                        default:
                            break
                    }
            })
    }
}
Related