Created
August 18, 2016 13:39
-
-
Save BrandonShega/5912eb3b9ff818d1c9be79e5cda953ca to your computer and use it in GitHub Desktop.
Counting Label
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class WCCountingLabel: UILabel { | |
private var start: CGFloat = 0 | |
private var end: CGFloat = 0 | |
private var progress: NSTimeInterval = 0 | |
private var lastUpdate: NSTimeInterval = 0 | |
private var totalTime: NSTimeInterval = 0 | |
private var easingRate: CGFloat = 0 | |
private var timer: CADisplayLink = CADisplayLink() | |
func countFrom(startValue: CGFloat, toEndValue endValue: CGFloat, withDuration duration: NSTimeInterval) { | |
start = startValue | |
end = endValue | |
// timer.invalidate() | |
if duration == 0.0 { | |
setTextValue(endValue) | |
return | |
} | |
easingRate = 3.0 | |
progress = 0 | |
totalTime = duration | |
lastUpdate = NSDate.timeIntervalSinceReferenceDate() | |
let displayLink = CADisplayLink(target: self, selector: #selector(WCCountingLabel.updateValue(_:))) | |
displayLink.frameInterval = 2 | |
displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) | |
displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: UITrackingRunLoopMode) | |
timer = displayLink | |
} | |
func setTextValue(endValue: CGFloat) { | |
let intValue = Int(endValue) | |
let numberFormatter = NSNumberFormatter() | |
numberFormatter.numberStyle = .DecimalStyle | |
text = numberFormatter.stringFromNumber(intValue) ?? "" | |
} | |
func updateValue(timer: NSTimer) { | |
let now = NSDate.timeIntervalSinceReferenceDate() | |
progress = progress + now - lastUpdate | |
lastUpdate = now | |
if progress >= totalTime { | |
timer.invalidate() | |
progress = totalTime | |
} | |
setTextValue(currentValue()) | |
} | |
func currentValue() -> CGFloat { | |
if progress >= totalTime { | |
return end | |
} | |
let percent = CGFloat(progress) / CGFloat(totalTime) | |
return start + (percent * (end - start)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment