【问题标题】:Split a custom UIView in different colors拆分不同颜色的自定义 UIView
【发布时间】:2021-06-14 15:15:51
【问题描述】:

我从情节提要制作了这个阶梯式进度条,并通过传递字符串数组(每个字符串添加一个步骤,因此标签和图标)以编程方式配置步骤数(最多 8 个)。

白色视图是基础视图,绿色视图是进度条,当然是 UIView。

要为进度设置动画,我只需设置进度条的宽度限制(我可以为指定步骤的百分比设置动画)。

现在,我的目标是将每个步骤的进度条分成不同的颜色:

例如,“Primo”步骤可以是蓝色,第二个步骤是红色等等,每个步骤都有不同的颜色。

我敢打赌我应该为进度条子类化 UIView,并在 draw 方法中发挥作用,但我的目标是将一系列步骤 (UIStackView) 传递给进度条并使用 setColor(forStep:1, color : .blue) 给定指定步骤的 frame.width。

你能帮帮我吗?

最佳。

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您可以在UIView.layer 中添加图层,如下所示 -

    class CustomProgress: UIView {
        var layersCache: [Int: CALayer] = [:]
        
        func setColor(forStep step: Int, color: UIColor) {
            let stepLayer: CALayer
            if let layer = layersCache[step] {
                stepLayer = layer
            } else {
                stepLayer = CALayer()
                layersCache[step] = stepLayer
            }
            
            let size = self.bounds.size
            let stepWidth = size.width / 8 /// totalSteps
            stepLayer.frame = CGRect(x: CGFloat(step) * stepWidth, y: 0, width: stepWidth, height: size.height)
            
            stepLayer.backgroundColor = color.cgColor
            self.layer.insertSublayer(stepLayer, at: 0)
        }
    }
    

    【讨论】:

    • 感谢您的回复 :) 最好在 customProgress.setColor 上说“从现在开始在帧宽度的这个位置设置这个颜色”作为参数传递 UIStackView(步骤本身)。用代码绘图很糟糕,哈哈
    猜你喜欢
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    • 2021-09-02
    • 2021-09-09
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多