【发布时间】:2019-06-05 12:53:59
【问题描述】:
我有一个来自 API 的 UIView 和百分比数字。我需要让 UIView 根据百分比填充一些颜色。
我从另一个问题中得到了基础知识。
class BadgeView: UIView {
private let fillView = UIView(frame: CGRect.zero)
private var coeff:CGFloat = 0.5 {
didSet {
// Make sure the fillView frame is updated everytime the coeff changes
updateFillViewFrame()
}
}
override func awakeFromNib() {
setupView()
}
private func setupView() {
// Setup the layer
layer.cornerRadius = bounds.height/2.0
layer.masksToBounds = true
// Setup filledView backgroundColor and add it as a subview
fillView.backgroundColor = UIColor(red: 220.0/255.0, green: 220.0/255.0, blue: 220.0/255.0, alpha: 0.4)
addSubview(fillView)
// Update fillView frame in case coeff already has a value
updateFillViewFrame()
}
private func updateFillViewFrame() {
fillView.frame = CGRect(x: 0, y: bounds.height*(1-coeff), width: bounds.width, height: bounds.height*coeff)
}
// Setter function to set the coeff animated. If setting it not animated isn't necessary at all, consider removing this func and animate updateFillViewFrame() in coeff didSet
public func setCoeff(coeff: CGFloat, animated: Bool) {
if animated {
UIView.animate(withDuration: 4.0, animations:{ () -> Void in
self.coeff = coeff
})
} else {
self.coeff = coeff
}
}
}
这是返回百分比的函数:
func cargaOKCheckStatus(resultado: NSDictionary) {
let JSON = resultado
if let ElapsedPercentual:Int = JSON.value(forKeyPath: "ResponseEntity.ElapsedPercentual") as? Int {
porcentaje = ElapsedPercentual
print(porcentaje)
}
}
API 返回 0%、10%、20%、30% 等。所以如果是 10%,UIView 应该用浅灰色填充 10%。现在,它总是半满。
【问题讨论】:
-
您可以使用
setNeedsLayout()或setNeedsDisplay()强制视图刷新UI。