I am animating a view in SwiftUI and it animates right when the view appears even if I don't have it in the .onAppear() method. I want it to animate only when I press the Text, that's why I am using the tap gesture. Here is my code:
struct ContentView: View {
var body: some View {
Text()
.scaleEffect(cardTap ? 0.9 : 1)
.gesture(LongPressGesture().onChanged { value in
self.cardTap = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.cardTap = false
UIImpactFeedbackGenerator(style: .soft).impactOccurred()
}
}
).animation(.spring(response: 0.5, dampingFraction: 0.5, blendDuration: 0))
}
}
By default, SwiftUI uses a fade animation to insert or remove views, but you can change that if you want by attaching a transition() modifier to a view.
To be exact, whenever you want to animate the view, you actually call layoutIfNeeded on the superview of that view. Try this instead: UIView. animate(withDuration: 0.1, delay: 0.1, options: UIViewAnimationOptions.
SwiftUI has built-in support for animations with its animation() modifier. To use this modifier, place it after any other modifiers for your views, tell it what kind of animation you want, and also make sure you attach it to a particular value so the animation triggers only when that specific value changes.
You can limit animation to be triggered by specific value only, like in below example
Text()
.scaleEffect(cardTap ? 0.9 : 1)
.gesture(LongPressGesture().onChanged { value in
self.cardTap = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.cardTap = false
UIImpactFeedbackGenerator(style: .soft).impactOccurred()
}
}
)
.animation(.spring(response: 0.5,
dampingFraction: 0.5, blendDuration: 0), value: cardTap) // << here !!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With