矩形进度条swiftUI

时间:2020-05-12 12:34:15

标签: swift animation swiftui ios-animations swiftui-environment

嘿,有人知道如何在swiftUI中创建矩形进度条吗?

像这样? https://i.stack.imgur.com/CMwB3.gif

我已经尝试过了:

struct ProgressBar: View
{
    @State var degress = 0.0
    @Binding var shouldLoad: Bool

    var body: some View
    {
        RoundedRectangle(cornerRadius: cornerRadiusValue)
            .trim(from: 0.0, to: CGFloat(degress))
            .stroke(Color.Scheme.main, lineWidth: 2.0)
            .frame(width: 300, height: 40, alignment: .center)
            .onAppear(perform: shouldLoad == true ? {self.start()} : {})
    }

    func start()
    {
        Timer.scheduledTimer(withTimeInterval: 0.3, repeats: true)
        {
            timer in

            withAnimation
            {
                self.degress += 0.3
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

这是[0..1]范围进度指示器的可能方法的简单演示。

通过Xcode 11.4 / iOS 13.4测试

demo

struct ProgressBar: View {
    @Binding var progress: CGFloat // [0..1]

    var body: some View {
        RoundedRectangle(cornerRadius: 10)
            .trim(from: 0.0, to: CGFloat(progress))
            .stroke(Color.red, lineWidth: 2.0)
            .animation(.linear)
    }
}

struct DemoAnimatingProgress: View {
    @State private var progress = CGFloat.zero

    var body: some View {
        Button("Demo") {
            if self.progress == .zero {
                self.simulateLoading()
            } else {
                self.progress = 0
            }
        }
        .padding()
        .background(ProgressBar(progress: $progress))
    }

    func simulateLoading() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            self.progress += 0.1
            if self.progress < 1.0 {
                self.simulateLoading()
            }
        }
    }
}

答案 1 :(得分:0)

可用于 XCode 12

import SwiftUI

//MARK: - ProgressBar
struct ContentView: View {
    
    @State private var downloaded = 0.0
    
    var body: some View {
        ProgressView("Downloaded...", value: downloaded, total: 100)
    }
}

//MARK: - Circular ProgressBar
struct ContentView: View {
        
    @State private var downloaded = 0.0
        
    var body: some View {
        ProgressView("Downloaded...", value: downloaded, total: 100)
            .progressViewStyle(CircularProgressViewStyle())
    }
}