1

So I want to animate an image in SwiftUI: after a user taps it, the image should be highlighted in a coloraturas (red or green, to indicate if the user tapped the right one). But after a few seconds it should go back to normal - aka as it looked at the start.

I also tried to make a custom highlight button which would've worked too, but it looks like it won't animate...

Currently I use a ZStack that animates a Color overlay if the user taps it, but I can't get a completion or something like that can I? How can I 'undo' the animation without user-interaction?

@State var redAlpha = 0.0

var badImg: some View{
    ZStack{
        Image(badImgName)
        .resizable()
        .scaledToFit()
        Button(action: {
            withAnimation {
                self.redAlpha = 0.5
            }
        }) {
            Color.clear
        }
        Color.red.opacity(self.redAlpha)  //<--overlay
    }
}
thisIsTheFoxe
  • 1,584
  • 1
  • 9
  • 30

1 Answers1

1

That's how you can animate view changes after some delay. Also you can change button to .tapAction

       ZStack {
            Image(badImgName)
                .resizable()
                .scaledToFit()
            Button(action: {
                withAnimation {
                    self.redAlpha = 0.5
                }
                DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                    withAnimation{ self.redAlpha = 0.0 }
                }
            }) {
                Color.clear
            }

            Color.red.opacity(self.redAlpha)  //<--overlay
        }

Might you need to call animation when view appear or disappear that easy to do with .onAppear .onDisappear

Radagast
  • 300
  • 1
  • 5
  • thanks m8, thought of `DispatchQueue` as well but thought.. idk.. it seems kinda hack-y.... whatevs.. works fine! Thx ^^ – thisIsTheFoxe Jul 15 '19 at 16:15
  • I also tried `.tapAction{...}` but for some reason it won't animate.. is that the intended behaviour or a beta-bug? .-. – thisIsTheFoxe Jul 15 '19 at 16:17