Swift UI loading indicator is not animating

Viewed 139

I am trying to implement a button in swift UI that will show a loading indicator on click. but after the button click, the loading indicator is not animating.

{
        Button(action: {
            self.isLoading = true
        }) {
            HStack {
                if isLoading {
                    Circle()
                        .trim(from: 0, to: 0.7)
                        .stroke(Color.green, lineWidth: 5)
                        .frame(width: 50, height: 50)
                        .rotationEffect(Angle(degrees: isLoading ? 360 : 0))
                        .animation(.default
                                    .repeatForever(autoreverses: false), value: isLoading)
                }
                    Text( isLoading ? "Processing" : "Submit")
                        .fontWeight(.semibold)
                        .font(.title)
                }
        }
        .frame(width: 250, height: 50)
        .background(.white)
    }

enter image description here

1 Answers

It should be different states: one for transition, one for progress. So it is better to separate progress into different view

Tested with Xcode 13.4 / iOS 15.5

Note: it's better to use linear animation in this case

demo

HStack {
    if isLoading {
        MyProgress()   // << here !!
    }
        Text( isLoading ? "Processing" : "Submit")
            .fontWeight(.semibold)
            .font(.title)
    }

and

struct MyProgress: View {
    @State var isLoading = false
    var body: some View {
        Circle()
            .trim(from: 0, to: 0.7)
            .stroke(Color.green, lineWidth: 5)
            .frame(width: 50, height: 50)
            .rotationEffect(Angle(degrees: isLoading ? 360 : 0))
            .animation(.linear
                        .repeatForever(autoreverses: false), value: isLoading)
            .onAppear {
                isLoading = true
            }
    }
}

Test module on GitHub

Related