iOS 一个实现数字增加效果的label

9 篇文章 0 订阅
本文讲解了一个自定义UILabel实现的计数器效果,结合数学公式展示数值变化,利用CADisplayLink控制动画过程。UI逻辑简洁,仅关注数值递增,适用于多种场景。核心代码展示了如何初始化、更新和停止计数动画。
摘要由CSDN通过智能技术生成

效果图

请添加图片描述

实现原理

数学原理

当前展示的数值 = 开始数值 + (结束数值 - 开始数值)* 当前时间进度(百分比)

UI逻辑

继承于UILabel , 只添加 数量增加功能,不涉及UI,UI样式完全外部定义,复用性好

核心代码

.h

@interface LBCountNumberLabel : UILabel

///  展示数量变化
/// @param start 开始数量
/// @param end 结束数量
/// @param timeInterval 时间
- (void)showFromStartNum:(NSInteger)start
                  endNum:(NSInteger)end
                duration:(CGFloat)timeInterval;

@end

NS_ASSUME_NONNULL_END

.m

#import "LBCountNumberLabel.h"

@interface LBCountNumberLabel ()

///计时器
@property (nonatomic, strong) CADisplayLink *link;
///开始时间
@property (nonatomic, assign) NSTimeInterval startTime;
///进度
@property (nonatomic, assign) CGFloat progress;
/// 总时长
@property (nonatomic, assign) CGFloat duration;
///开始值
@property (nonatomic, assign) NSInteger startValue;
///结束值
@property (nonatomic, assign) NSInteger endValue;
///当前展示的值
@property (nonatomic, assign) NSInteger currentValue;

@end

@implementation LBCountNumberLabel

- (void)showFromStartNum:(NSInteger)statr
                  endNum:(NSInteger)end
                duration:(CGFloat)timeInterval
{
    self.startValue = statr;
    self.endValue = end;
    self.duration = timeInterval;
    self.currentValue = statr;
    [self.link addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}

- (void)linkSelector
{
    if (self.currentValue >= self.endValue) {
        self.currentValue = self.endValue;
        self.text = [NSString stringWithFormat:@"%ld",self.currentValue];
        [self.link invalidate];
        self.link = nil;
        return;
    }
    NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate];
    if (self.startTime == 0) {
        self.startTime = now;
    }
    self.currentValue = self.startValue + (self.endValue - self.startValue) * (now - self.startTime) / self.duration;
    self.text = [NSString stringWithFormat:@"%ld",self.currentValue];
}

#pragma mark - lazy load

- (CADisplayLink *)link
{
    if (!_link) {
        _link = [CADisplayLink displayLinkWithTarget:self selector:@selector(linkSelector)];
        /// 每秒钟的帧数
        _link.preferredFramesPerSecond = 10;
    }
    return _link;
}

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值