ZZCountingLabel.m 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. //
  2. // ZZCountingLabel.m
  3. // 动画测试
  4. //
  5. // Created by 周兴 on 2017/6/29.
  6. // Copyright © 2017年 周兴. All rights reserved.
  7. //
  8. #import "ZZCountingLabel.h"
  9. @interface ZZCountingLabel ()
  10. @property (nonatomic, strong) CADisplayLink *playLink;
  11. @property (nonatomic, assign) NSInteger displayPerSecond;
  12. @property (nonatomic, assign) CGFloat fromValue;
  13. @property (nonatomic, assign) CGFloat toValue;
  14. @property (nonatomic, assign) CGFloat increaseValue;
  15. @property (nonatomic, assign) CGFloat perValue;
  16. @end
  17. @implementation ZZCountingLabel
  18. - (instancetype)init {
  19. if (self = [super init]) {
  20. [self initValues];
  21. }
  22. return self;
  23. }
  24. - (instancetype)initWithFrame:(CGRect)frame {
  25. if (self = [super initWithFrame:frame]) {
  26. [self initValues];
  27. }
  28. return self;
  29. }
  30. - (void)awakeFromNib {
  31. [super awakeFromNib];
  32. [self initValues];
  33. }
  34. - (void)initValues {
  35. _duration = 2.0;
  36. _displayPerSecond = 30;
  37. }
  38. - (void)countingFrom:(CGFloat)fromValue to:(CGFloat)toValue {
  39. [self countingFrom:fromValue to:toValue duration:_duration];
  40. }
  41. - (void)countingFrom:(CGFloat)fromValue to:(CGFloat)toValue duration:(CGFloat)duration {
  42. _fromValue = fromValue;
  43. _toValue = toValue;
  44. _duration = duration;
  45. _increaseValue = _fromValue;
  46. _perValue = (_toValue - _fromValue)/(_duration==0?1:(_displayPerSecond*_duration));
  47. if (self.playLink) {
  48. [self.playLink invalidate];
  49. self.playLink = nil;
  50. }
  51. CADisplayLink *playLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(countingAction)];
  52. if (@available(iOS 10.0, *)) {
  53. playLink.preferredFramesPerSecond = _displayPerSecond;
  54. } else {
  55. playLink.frameInterval = 60/(_displayPerSecond==0?1:_displayPerSecond);
  56. }
  57. [playLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
  58. [playLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:UITrackingRunLoopMode];
  59. self.playLink = playLink;
  60. }
  61. - (void)countingAction {
  62. _increaseValue += _perValue;
  63. if (_fromValue < _toValue) {
  64. if (_increaseValue >= _toValue) {
  65. [self stopDisplayLink];
  66. }
  67. } else {
  68. if (_increaseValue <= _toValue) {
  69. [self stopDisplayLink];
  70. }
  71. }
  72. dispatch_async(dispatch_get_main_queue(), ^{
  73. self.text = [NSString stringWithFormat:@"%.0f%%",_increaseValue];
  74. });
  75. }
  76. - (void)stopDisplayLink {
  77. [self.playLink invalidate];
  78. self.playLink = nil;
  79. _increaseValue = _toValue;
  80. }
  81. @end