2014-10-01 48 views
1

我在我的應用程序中有一個圓形的進度條,它似乎工作得很好。但是,出於某種原因,我無法讓進度條縮小。無法將進度條重置爲0%

基本上它的功能是顯示他們花費的用戶預算的百分比。但是,用戶也可以添加信用交易,當然,由於他們增加了總預算,因此您期望減少進度欄。但似乎沒有這樣做。當預算重置時,我也需要將其重置爲0%,這不起作用。

下面是進步圈代碼:

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)) 

    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) 
    CGContextDrawImage(ctx, self.bounds, UIImage(named: "RadialProgressFill").CGImage) 
    CGContextRestoreGState(ctx) 
} 

這是我目前如何嘗試重置:

progress = 0.00 

這就是進步是如何計算的:

 percent = 100*totalSpendingsCounter/(currencyDouble + totalCreditCounter) 
    let nf = NSNumberFormatter() 
    nf.numberStyle = .DecimalStyle 

    if percent > 100 { 
     percentageDisplay.text = "100%" 
    } else { 
     var percentString = nf.stringFromNumber(percent) + "%" 
     percentageDisplay.text = percentString 
    } 

    progress = CGFloat(percent/100) 

有沒有想法?

回答

2

首先,進度應該是ProgressCircle的屬性,而不是全局變量的屬性。其次,它需要在設置時標記爲需要重新顯示:

class ProgressCircle: UIView { 

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

    (The rest of your code...) 
+0

啊,那麼setNeedsDisplay()函數應該做什麼? – user3746428 2014-10-02 21:51:22

+1

這是默認的內置方法,它是UIView的一部分。它告訴它需要重繪自己的視圖。 – 2014-10-03 20:58:44

+0

啊,明白了。非常感謝。 – user3746428 2014-10-03 21:16:47