Warm tip: This article is reproduced from stackoverflow.com, please click
swift swiftui xcode swift5

On Appear only works for 1st instance... how can I change that

发布于 2020-04-03 23:48:45

I have a section of code that makes my text appear mid screen and pulse in and out briefly, perfect. BUT it only does it the first time the function is called. The following times it shows the text but not the animation.

VStack {
    GameView(showText: self.$showText, imageName: self.$imageName)
    Button(action: {
        withAnimation {
            self.showText.toggle()
            self.attempts += 1

        }
    }, label: {
        Text("Show / Hide Text")
    })
}
    if self.showText {
        VStack {
            Spacer()
            HStack {
                Spacer()
                Image(imageName)
                //animation here
                .scaleEffect(scale)

                    .onAppear{

                        let baseAnimation = Animation.easeInOut(duration: 0.5)
                        let repeated = baseAnimation.repeatForever(autoreverses: true)

                        return withAnimation(repeated) {
                            self.scale = 0.5


                        }


                }

                Spacer()
            }
            Spacer()
        }


    }


}

should I be using something other than On Appear?

thanks Always Striving

Questioner
Lynxbci
Viewed
61
Asperi 2020-01-31 23:14

On hide it is not reset scale state, so no changes in state on next show, so no animation. Just add below .onAppear

.onDisappear {
    self.scale = 1
}