cell 中使用定时器做倒计时时候涉及到滚动时候的重用,项目中虽然用的不多,但是遇到后一时想不到更好的办法,还是一个蛋疼的事
下面总结一个cell中做倒计时的方法:
@interface ZYTableViewCell()
@property (nonatomic,strong) UILabel *label;
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,assign) int currentTime;
@end
@implementation ZYTableViewCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
[self addSubviews];
}
return self;
}
- (void)addSubviews {
_label = [[UILabel alloc] init];
[self.contentView addSubview:_label];
_label.frame = CGRectMake(0, 7, 200, 30);
_label.textColor = [UIColor redColor];
_label.font = [UIFont systemFontOfSize:28];
}
- (void)setupWithTime:(int)newTime {
// 主要是这个公式:
// double countDownTime = newTime + refreshTime - time(NULL);
// newTime 从服务端请求对应的数据倒计时的时间撮,服务端保存的对应商品的时间撮,动态的每次亲求豆不一样
// refreshTime 从服务端请求数据返回时的时间撮,本地缓存的最新一次请求返回的时间 在数据返回时候refreshTime = time(NULL);来缓存
// time(NULL) 当前最新时间撮
//下面推导公式是怎么来的
//假设 商品的倒计时时间是40秒——> newTime
//cur(最开始)为数据请求时候的时间撮:A = time(NULL);——> refreshTime
//随着倒计时的进行一秒后 B = time(NULL);——>time(NULL)
// 随着倒计时的进行2秒后 C = time(NULL);——>time(NULL)
// ....
//随着倒计时的进行 N = time(NULL);——>time(NULL)
//那么获得2秒后当前倒计时进行的时间为
//40-(C-A) = 38 (当前倒计时时间)
// newTime-(time(NULL)-refreshTime)
// newTime + refreshTime - time(NULL);
//本地做个测试, refreshTime 替换为 1490072438(最好比time(NULL)大点)
double countDownTime = newTime + 1490072438 - time(NULL);
_currentTime = countDownTime;
if (countDownTime <= 0) {
_label.text = @"00:00:00";
if (_timer) {
[_timer invalidate];
_timer = nil;
}
return;
}
if (_timer == nil) {
_timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timeTask) userInfo:nil repeats:YES];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:_timer forMode:NSRunLoopCommonModes];
}
[_timer fire];
}
- (void)timeTask {
if (_currentTime <= 0) {
_label.text = @"00:00:00";
}
int second = (int)_currentTime % 60;
int minute = ((int)_currentTime / 60) % 60;
int hours = _currentTime / 3600;
_label.text = [NSString stringWithFormat:@"%02d:%02d:%02d",hours,minute,second];
if (_currentTime<=0) {
[_timer invalidate];
_timer = nil;
return;
}
_currentTime--;
}
@end
网友评论