ios 数字 积分跳跃式出现

2020-03-12  本文已影响0人  天上飞的狒狒
ezgif.com-video-to-gif (1).gif

需要封装一个 JumpNumberView
.h文件

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface JumpNumberView : UIView
@property (nonatomic, copy) NSString *endNumberString;
@end

NS_ASSUME_NONNULL_END

.m文件

#import "JumpNumberView.h"

@interface JumpNumberView()
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger showNumber;
@property (nonatomic, assign) NSInteger endNumber;
@property (nonatomic, assign) NSInteger avterNumber;
@property (nonatomic, strong) UILabel *showAmountLabel;
@end

@implementation JumpNumberView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.showAmountLabel = [[UILabel alloc] initWithFrame:self.bounds];
        [self addSubview:self.showAmountLabel];
        self.showAmountLabel.textColor = [UIColor blackColor];
    }
    return self;
}
- (void)setEndNumberString:(NSString *)endNumberString{
    if (_endNumberString != endNumberString) {
        _endNumberString = endNumberString;
    }
    NSInteger endNum = [endNumberString integerValue];
    [self beginShowActionWithEndNum:endNum];
}
- (void)beginShowActionWithEndNum:(NSInteger)endNumber{
    self.showNumber = 0;
    self.endNumber = endNumber;
    self.timer = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(jumpNumberAnimation:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    self.avterNumber = endNumber/8;
}

- (void)stopShowAction:(id)sender {
     [self.timer invalidate];
}

- (void)jumpNumberAnimation:(NSTimer *)timer  {
    self.showAmountLabel.text = [NSString stringWithFormat:@"%lu",self.showNumber];
    self.showNumber = self.showNumber + self.avterNumber;
    if (self.showNumber >= self.endNumber) {
         self.showAmountLabel.text  = [NSString stringWithFormat:@"%lu",self.endNumber];;
        [self.timer invalidate];
    }
}

调用

#import "ViewController.h"
#import "JumpNumberView.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    JumpNumberView *numberView = [[JumpNumberView alloc] initWithFrame:CGRectMake(50, 100, 100, 40)];
    numberView.backgroundColor = [UIColor redColor];
    [self.view addSubview:numberView];
    numberView.endNumberString = @"10002";
    
}


@end
上一篇下一篇

猜你喜欢

热点阅读