gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:04:56 24 4
gpt4 key购买 nike

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

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

谢谢!

最佳答案

如果你想用 swift 得到答案,这里是来自 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()
}
}

在 Playground 进行测试

关于ios - UIProgressBar:如何根据背景颜色更改UILabel颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52824770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com