Last active
September 4, 2016 18:59
-
-
Save Calvin-Huang/670d7573695dfc8b9c0dae127a2dd5fc to your computer and use it in GitHub Desktop.
Independent view component - CountingLabel, inherited from UILabel - https://github.com/Calvin-Huang/CHCountingLabel/blob/ec5fdbe924f34c9deec4017755b1dde95e33f4d8/Animation-Issue/CountingLabel.swift
This file contains 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 CountingLabel: UILabel { | |
enum CountingMode: Int { | |
case Decrease = -1 | |
case Increase = 1 | |
} | |
var countingMode: CountingMode = .Decrease | |
var isCounting: Bool = false | |
var isPause: Bool = false | |
var textFormatter: ((value: Int) -> String) = { value -> String in | |
return String(value) | |
} | |
private var timer: NSTimer? | |
private var startTimeStamp: Int = 0 | |
private var startCountingValue: Int = 0 | |
private var countingValue: Int = 0 | |
// MARK: - Selectors | |
func updateCountingLabel(_: NSTimer) { | |
let currentTimeStamp = Int(NSDate().timeIntervalSince1970) | |
let progress = countingValue + (currentTimeStamp - startTimeStamp) * countingMode.rawValue | |
self.text = textFormatter(value: progress) | |
} | |
// MARK: - Public Methods | |
func start() { | |
if timer == nil { | |
guard let labelText = self.text, let currentValue = Int(labelText) else { | |
return | |
} | |
startTimeStamp = Int(NSDate().timeIntervalSince1970) | |
if !isPause { | |
startCountingValue = currentValue | |
} | |
countingValue = currentValue | |
timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(updateCountingLabel(_:)), userInfo: nil, repeats: true) | |
isCounting = true | |
isPause = false | |
} | |
} | |
func pause() { | |
timer?.invalidate() | |
timer = nil | |
isCounting = false | |
isPause = true | |
} | |
func stop() { | |
pause() | |
isPause = false | |
self.text = textFormatter(value: startCountingValue) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment