我的应用中有一个循环进度条,显示用户所花费的预算百分比。它似乎有效,但除非我在多任务中关闭应用程序并重新打开它,否则它不会更新。
在做了一些研究后,我发现我应该用setNeedsDisplay重新加载它,但是这并没有解决问题。
这是我的drawRect()代码:
var progress: CGFloat = 0
class ProgressCircle: UIView {
override func drawRect(rect: CGRect) {
var ctx = UIGraphicsGetCurrentContext()
var innerRadiusRatio: CGFloat = 0.6
var path: CGMutablePathRef = CGPathCreateMutable()
var startAngle: CGFloat = CGFloat(-M_PI_2)
var endAngle: CGFloat = CGFloat(-M_PI_2) + min(1.0, progress) * CGFloat(M_PI * 2)
var outerRadius: CGFloat = CGRectGetWidth(self.bounds) * 0.5 - 1.0
var innerRadius: CGFloat = outerRadius * innerRadiusRatio
var center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect))
//Code for background circle
var context: CGContextRef = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, (UIColor.darkGrayColor()).CGColor)
var rectangle: CGRect = CGRectMake(0, 0, 171, 171)
CGContextBeginPath(context)
CGContextAddEllipseInRect(context, rectangle)
CGContextDrawPath(context, kCGPathFill)
UIGraphicsEndImageContext()
CGContextSetFillColorWithColor(context, (UIColorFromRGB(0xEAEAEA)).CGColor)
var rectangleSmall: CGRect = CGRectMake(35.95, 35.95, 99.1, 99.1) //102.6
CGContextBeginPath(context)
CGContextAddEllipseInRect(context, rectangleSmall)
CGContextDrawPath(context, kCGPathFill)
UIGraphicsEndImageContext()
//Code for progress radius
CGPathAddArc(path, nil, center.x, center.y, innerRadius, startAngle, endAngle, false)
CGPathAddArc(path, nil, center.x, center.y, outerRadius, endAngle, startAngle, true)
CGPathCloseSubpath(path)
CGContextAddPath(ctx, path)
CGContextSaveGState(ctx)
CGContextClip(ctx)
if percent > 100 {
CGContextDrawImage(ctx, self.bounds, UIImage(named: "RadialProgressFillOver").CGImage)
} else {
CGContextDrawImage(ctx, self.bounds, UIImage(named: "RadialProgressFill").CGImage)
}
CGContextRestoreGState(ctx)
}
这就是我尝试重新加载进度圈的方法:
override func viewDidAppear(animated: Bool) {
//Show set up screen if user hasn't used AffordIt before.
userReturned = NSUserDefaults.standardUserDefaults().boolForKey("userReturnedCheck")
if userReturned == false {
self.performSegueWithIdentifier("setupView", sender: self)
}
//Add circular progress bar to budget display view.
progress = CGFloat(percent/100)
var circleFrame = CGRect(x: 75, y: 249, width: 171, height: 171)
var circle = ProgressCircle(frame: circleFrame)
self.budgetDisplayView.addSubview(circle)
self.budgetDisplayView.sendSubviewToBack(circle)
circle.setNeedsDisplay()
view.setNeedsDisplay()
circle.backgroundColor = UIColor.clearColor()
}