Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI animating the width of RoundedRectangle from 0 to width onAppear?

I thought I had written this correctly, but the RoundedRectangle isn't animating...What am I missing? 🤔

struct BarView: View {
    
    var progress: Double = 0.0
    
     var progressAnimation: Animation {
        Animation
            .linear
            .speed(0.5)
            .delay(0.02)
     }
    
    var body: some View {
        
        ZStack {
                ZStack(alignment: .leading) {
                    RoundedRectangle(cornerRadius: 12.0)
                        .fill(Color(.lightGray))
                        .opacity(0.1)
                        .frame(height: 15)
                        .overlay(GeometryReader { geometry in
                    RoundedRectangle(cornerRadius: 12.0)
                        .fill(getColorForBar(progress: progress))
                        .frame(width: getFillWidth(progress: progress, geometry: geometry), height: 15)
                        .animation(self.progressAnimation)
                         }, alignment: .leading)
                }
        }
    }
like image 405
GarySabo Avatar asked Nov 14 '25 12:11

GarySabo


1 Answers

Here is a bit modified code that works with Xcode 12.1 / iOS 14.1. So the issue might be either in place of usage or in getFillWidth function.

demo

struct TestBarView: View {
    @State private var value = 0.0
    var body: some View {
        BarView(progress: value)
            .onAppear {
                value = 0.8
            }
    }
}

struct BarView: View {
    
    var progress: Double = 0.0
    
    var progressAnimation: Animation {
        Animation
            .linear
            .speed(0.5)
            .delay(0.02)
    }
    
    var body: some View {
        
        ZStack {
            ZStack(alignment: .leading) {
                RoundedRectangle(cornerRadius: 12.0)
                    .fill(Color(.lightGray))
                    .opacity(0.1)
                    .frame(height: 15)
                    .overlay(GeometryReader { geometry in
                        RoundedRectangle(cornerRadius: 12.0)
                            .fill(Color.blue)
                            .frame(width: geometry.size.width * CGFloat(progress), height: 15)
                            .animation(self.progressAnimation)
                    }, alignment: .leading)
            }
        }
    }
}
like image 129
Asperi Avatar answered Nov 17 '25 10:11

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!