Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Animate Image on Button

Using SwiftUI, I'm trying to show an animated image and hide the text when the user clicks the button. Here is my code:

@State private var showingActivity = false

var body: some View {
    Button(action: {
        self.showingActivity.toggle()
    }) { 
        HStack {
            if self.showingActivity {
                Image(systemName: "arrow.2.circlepath")
                    .font(.system(size: 29))
                    .rotationEffect(.degrees(self.showingActivity ? 360.0 : 0.0))
                    .animation(Animation.linear(duration: 1.5).repeatForever(autoreverses: false))
            }
            else {
                Text("Continue")
            }
        }
    }
}

The Continue text appears and when clicked it disappears (as expected) and the image shows, but no animation. Any ideas what I might be doing wrong.

Thanks

like image 670
user9041624 Avatar asked Sep 06 '25 04:09

user9041624


1 Answers

or try this:

struct ImageView : View {

    @State private var showAction = false

    var body: some View {
        Image(systemName: "arrow.2.circlepath")
            .font(.system(size: 29))
            .rotationEffect(.degrees(self.showAction ? 360.0 : 0.0))
            .animation(self.showAction ? Animation.linear(duration: 1.5).repeatForever(autoreverses: false) : nil)
        .onAppear() {
            self.showAction = true
        }
    }
}

struct ContentView: View {
    @State private var showingActivity = false

    var body: some View {
        Button(action: {
            self.showingActivity.toggle()
        }) {
            HStack {
                if self.showingActivity {
                    ImageView()
                }
                else {
                    Text("Continue")
                }
            }
        }
    }
}
like image 123
Chris Avatar answered Sep 11 '25 03:09

Chris