HowTo —— SwiftUI2.0 使用 ProgressView 显示进度条

SwiftUI2.0 新增了一些便捷的内置控件,比如说 Label、ProgressView 等。其基本形态都很普通,不过都支持自定义 style。官方的意图也比较明显,通过内置控件,规范代码、提高原型编写速度,如需要更精细控制可通过扩展 style 来完成。

健康笔记 - 新生活从记录开始

健康笔记是一款智能的数据管理和分析工具,让您完全掌控自己和全家人的健康信息。作为慢性病患者,肘子深知健康管理的重要与难度。创建健康笔记的初心,就是要为您提供一款轻松高效的健康信息记录与分析工具

推荐

经典小菊花

ProgressView()
progress1

线性进度条

ProgressView("完成量", value: 50, total: 100)
截屏 2020-07-11 下午 4.09.34

代码示例

import SwiftUI

struct ProgressTest: View {
    @State var timer = Timer.TimerPublisher(interval: 0.03, runLoop: .main, mode: .common).autoconnect()
    @State var value:Double = 0.0
    var body: some View {
        List{
            //无法定义颜色
            ProgressView()
            
            //无法隐藏 Label
            ProgressView("完成量", value: value, total: 100)
                .accentColor(.red)
            //自定义 Style
            ProgressView("工程进度",value: value, total: 100)
                .progressViewStyle(MyProgressViewStyle())
        }
        .onAppear {
            timer = Timer.TimerPublisher(interval: 0.03, runLoop: .main, mode: .common).autoconnect()
        }
        .onReceive(timer) { _ in
            if value < 100 {
                value += 2
            }
        }
    }
}

//定义方法都大同小异。
struct MyProgressViewStyle:ProgressViewStyle{
    let foregroundColor:Color
    let backgroundColor:Color
    init(foregroundColor:Color = .blue,backgroundColor:Color = .orange){
        self.foregroundColor = foregroundColor
        self.backgroundColor = backgroundColor
    }
    func makeBody(configuration: Configuration) -> some View {
        GeometryReader{ proxy in
            ZStack(alignment:.topLeading){
            backgroundColor
            Rectangle()
                .fill(foregroundColor)
                .frame(width:proxy.size.width * CGFloat(configuration.fractionCompleted ?? 0.0))
            }.clipShape(RoundedRectangle(cornerRadius: 10))
            .overlay(
                    configuration.label
                        .foregroundColor(.white)
            )
        }
    }
}
如果您发现本文对您有所帮助或者享受阅读,请考虑捐赠以支持我的写作。您的贡献将帮助我继续为您创造有价值的内容。

通过 进行捐赠。

欢迎通过 TwitterDiscord 频道 或下方的留言板与我进行交流。

本博客文章采用 CC 4.0 协议,转载需注明出处和作者。