You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Swift实现分段进度条效果?

Swift 分段进度条实现方案

完全可以使用Swift复刻你需要的分段进度条效果,核心实现逻辑是将进度条拆分为多个独立的分段单元,单独控制每个单元的填充状态,支持UIKit和SwiftUI两种实现方式:

SwiftUI 实现示例

struct SegmentedProgressBar: View {
    /// 总分段数量
    let totalSegments: Int
    /// 已完成的分段数量
    let completedSegments: Int
    /// 分段之间的间距
    private let segmentSpacing: CGFloat = 4
    /// 进度条高度
    private let barHeight: CGFloat = 8

    var body: some View {
        HStack(spacing: segmentSpacing) {
            ForEach(0..<totalSegments, id: \.self) { index in
                RoundedRectangle(cornerRadius: barHeight / 2)
                    .fill(index < completedSegments ? .blue : .gray.opacity(0.3))
                    .frame(height: barHeight)
            }
        }
        .frame(maxWidth: .infinity)
    }
}

// 调用方式示例:生成分5段、已完成3段的进度条
// SegmentedProgressBar(totalSegments: 5, completedSegments: 3)

你可以根据需求自定义颜色、圆角大小、分段间距、进度条高度,也可以修改逻辑支持半填充的分段效果。

UIKit 实现示例

class SegmentedProgressBar: UIView {
    private let totalSegments: Int
    private let completedSegments: Int
    private let segmentSpacing: CGFloat = 4
    private let barHeight: CGFloat = 8

    init(totalSegments: Int, completedSegments: Int, frame: CGRect) {
        self.totalSegments = totalSegments
        self.completedSegments = completedSegments
        super.init(frame: frame)
        setupSegmentViews()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupSegmentViews() {
        let totalSpacing = segmentSpacing * CGFloat(totalSegments - 1)
        let singleSegmentWidth = (frame.width - totalSpacing) / CGFloat(totalSegments)

        for index in 0..<totalSegments {
            let segmentX = CGFloat(index) * (singleSegmentWidth + segmentSpacing)
            let segmentY = (frame.height - barHeight) / 2
            let segmentFrame = CGRect(x: segmentX, y: segmentY, width: singleSegmentWidth, height: barHeight)
            let segmentView = UIView(frame: segmentFrame)
            segmentView.backgroundColor = index < completedSegments ? .systemBlue : .systemGray4
            segmentView.layer.cornerRadius = barHeight / 2
            addSubview(segmentView)
        }
    }
}

如果需要支持进度动态更新,给completedSegments属性添加didSet监听,触发UI重绘即可。

内容的提问来源于stack exchange,提问作者kelson_99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 20:36:00