Animate an animated gif only while pressing the button

Viewed 55

This is my code :

struct Animation: View {
       var body: some View{
           Image("Animation.gif")
       }
   }

i have a gif image and i want this image to only be animated once a button click only, i need help!

and if there is no button click then it won't be animated thank you

1 Answers

As far as I know, SwiftUI doesn't have anything that can do this. Instead, you should use an @State variable to track whether or not the button has been pressed. If it hasn't, show a non-animated image, and if it has, show a different image, but animated this time.

Something like this:

@State var buttonIsClicked = false

let nonAnimated = <static image>
let animated = <your gif>

var body: some View {
    VStack {
        if buttonIsClicked {
            animated
        } else {
            nonAnimated
        }

      
        Button("Click to animate") {
            buttonIsClicked.toggle()
        }
    }
}
Related