UIProgressBar:如何根据背景色更改UILabel颜色

时间:2018-10-15 21:07:12

标签: ios swift uiprogressbar

我是iOS编程的新手。我想创建一个带有UIlabel的进度条,它也可以根据背景颜色更改文本颜色,例如:sample image

不要将问题标记为重复。因为我找到的解决方案在 Obj C 或某些Pod中。但是我想要Swift中的解决方案,因为我对Obj-C没有任何了解。

谢谢!

1 个答案:

答案 0 :(得分:0)

如果您想快速获得答案,请参见以下post中的代码(从objc更改为swift),该代码正是您所需要的:

这很快4

class MyProgressView: UIView {

    var progress: CGFloat = 0 {
        didSet {
            setNeedsDisplay()
        }
    }

    override func draw(_ rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()

        // Set up environment.
        let size = bounds.size
        let backgroundColor = UIColor(red: 108/255, green: 200/255, blue: 226/255, alpha: 1)
        let foregroundColor = UIColor.white
        let font = UIFont.boldSystemFont(ofSize: 42)

        // Prepare progress as a string.
        let progress = NSString(format: "%d%%", Int(round(self.progress * 100))) // this cannot be a String because there are many subsequent calls to NSString-only methods such as `size` and `draw`
        var attributes: [NSAttributedString.Key: Any] = [.font: font]
        let textSize = progress.size(withAttributes: attributes)
        let progressX = ceil(self.progress * size.width)
        let textPoint = CGPoint(x: ceil((size.width - textSize.width) / 2), y: ceil((size.height - textSize.height) / 2))

        // Draw background + foreground text
        backgroundColor.setFill()
        context?.fill(bounds)
        attributes[.foregroundColor] = foregroundColor
        progress.draw(at: textPoint, withAttributes: attributes)

        // Clip the drawing that follows to the remaining progress's frame
        context?.saveGState()
        let remainingProgressRect = CGRect(x: progressX, y: 0, width: size.width - progressX, height: size.height)
        context?.addRect(remainingProgressRect)
        context?.clip()

        // Draw again with inverted colors
        foregroundColor.setFill()
        context?.fill(bounds)
        attributes[.foregroundColor] = backgroundColor
        progress.draw(at: textPoint, withAttributes: attributes)

        context?.restoreGState()
    }
}

在游乐场测试过