Swift UI animation diagonal instead horizontal

640 views Asked by At

I'm trying to make a loading view with some animations, but instead of the RoundRectangle offset it self horizontaly as it's defined in the code, it is actually moving in diagonal.

Why is it animating in diagonal?

Here's my struct:

struct LoadingIndicator: View {
    let textToDisplay:String
    @State private var isLoading:Bool = false
    
    var body: some View {
        ZStack {
            Text(textToDisplay)
                .fontWeight(.bold)
                .offset(x: 0, y: -25)
            
            RoundedRectangle(cornerRadius: 3)
                .stroke(Color.gray, lineWidth: 3)
                .frame(width: 250, height: 3)
            
            RoundedRectangle(cornerRadius: 3)
                .stroke(Color.indigo, lineWidth: 3)
                .frame(width: 30, height: 3)
                .offset(x: (isLoading ? 110 : -110), y: 0)
                .animation(.linear(duration: 1).repeatForever(), value: isLoading)
        }.onAppear {
            self.isLoading = true
        }
    }
    
}

This is what I got:

enter image description here

This is what I wanted to achieve: enter image description here

1

There are 1 answers

0
Fred Novack On BEST ANSWER

After seing this question: SwiftUI: Broken explicit animations in NavigationView?

I solved my problem:

struct LoadingIndicator: View {
    let textToDisplay:String
    @State private var isLoading:Bool = false
    
    var body: some View {
        ZStack {
            Text(textToDisplay)
                .fontWeight(.bold)
                .offset(x: 0, y: -25)
            
            RoundedRectangle(cornerRadius: 3)
                .stroke(Color.gray, lineWidth: 3)
                .frame(width: 250, height: 3)
            
            RoundedRectangle(cornerRadius: 3)
                .stroke(Color.indigo, lineWidth: 3)
                .frame(width: 30, height: 3)
                .offset(x: (isLoading ? 110 : -110), y: 0)
                .animation(.linear(duration: 1).repeatForever(), value: isLoading)
        }.onAppear {
            DispatchQueue.main.async {
                self.isLoading = true
            }
            
        }
    }
}