Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

ios - 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)
                }
        }
    }
question from:https://stackoverflow.com/questions/65912447/swiftui-animating-the-width-of-roundedrectangle-from-0-to-width-onappear

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...