在 Image SwiftUI 上点击动画

xme*_*tal 4 animation image gesture swift swiftui

如何在图像上制作动画,以便当我点击它并按住它时它会向后缩放,当我释放它时图像会恢复到其原始大小?

struct ContentView: View {
    var body: some View {
        Image(systemName: "heart")
        .onTapGesture {
        // Gesture when held down and released
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Asp*_*eri 6

这是可能解决方案的演示。使用 Xcode 12 / iOS 14 进行测试。

演示

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
                    }
            })
    }
}
Run Code Online (Sandbox Code Playgroud)