Rectangle progress bar swiftUI

≯℡__Kan透↙ 提交于 2020-06-08 13:13:02

问题


Hey does someone know how can I create rectangle progress bar in swiftUI?

Something like this? https://i.stack.imgur.com/CMwB3.gif

I have tried this:

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

回答1:


Here is simple demo of possible approach for [0..1] range progress indicator.

Tested with Xcode 11.4 / iOS 13.4

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


来源:https://stackoverflow.com/questions/61751863/rectangle-progress-bar-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!