Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a view from animating on appear in SwiftUI?

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))
     }
}
like image 554
Susca Bogdan Avatar asked Jul 13 '20 09:07

Susca Bogdan


People also ask

How do I delete a view in SwiftUI?

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.

How do I view an animation in Swift?

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.

How do I animate in SwiftUI?

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.


1 Answers

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 !!
like image 184
Asperi Avatar answered Nov 15 '22 12:11

Asperi