'How do I animate exchanging one image for another in SwiftUI?
I am exchanging one image for another in a view as a result of a tap, double-tap, or drag gesture, and I would like to animate the transition between images. As shown below, I'm using withAnimation within onEnded for both the tapDouble and the horizontal drag gestures. (The animation is omitted from the other gestures for comparison.) In neither case does refreshing the view behave differently from the unanimated gestures. I would appreciate help in figuring out how to animate the replacement of an image.
struct PieceView: View {
var id: String
var ext: String
@State private var image: Image
var drag: some Gesture {
DragGesture()
.onEnded { gesture in
if abs(gesture.translation.width) > abs(gesture.translation.height) {
withAnimation(.easeIn(duration: 2.0)) {
image = Image(id + "4")
}
flipHorizontal()
} else {
image = Image(id + "6")
flipVertical()
}
}
}
var tapSingle: some Gesture {
TapGesture()
.onEnded{_ in
image = Image(id + "1")
rotateRight()
}
}
var tapDouble: some Gesture {
TapGesture(count: 2)
.onEnded{_ in
withAnimation(.easeIn(duration: 2.0)) {
image = Image(id + "3")
}
rotateLeft()
}
}
var body: some View {
ZStack {
image
.gesture(drag)
Image("emptySquare")
.padding(0)
.gesture(tapSingle)
.highPriorityGesture(tapDouble)
}
}
init() {
id = ""
ext = ""
image = Image("")
}
init(id: String, ext: String = "0") {
self.id = id
self.ext = ext
self.image = Image(id + ext)
}
func rotateRight() -> () {
print ("\(id) rotated right")
}
func rotateLeft() -> () {
print ("\(id) rotated left")
}
func flipHorizontal() -> () {
print ("\(id) flipped horizontal")
}
func flipVertical() -> () {
print ("\(id) flipped vertical")
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
