在最近的開發(fā)中遇到了一個(gè)需求赊瞬,要在tableview 揭曉接下來正要展示的倒計(jì)時(shí)展示即將揭曉的物品食侮,倒計(jì)時(shí)展示類似這個(gè)demo
demo 地址: https://github.com/heysunnyboy/leftTimeDemo.git
(關(guān)鍵詞:倒計(jì)時(shí))聽到這個(gè)上面的這個(gè)需求,第一點(diǎn)你會(huì)想到什么了,定時(shí)器沒錯(cuò)委可,接下來是cell 里面放定時(shí)器 嗎,那么如果是這樣的話會(huì)產(chǎn)生什么樣的后果呢腊嗡,
我一開始也是這樣想的着倾,然后tableview 顯示出來沒多久,由于創(chuàng)建的定時(shí)器過多程序就卡死了燕少,cell 的高度100左右 卡者,在iphone 6的屏幕大致創(chuàng)建 至少6個(gè)定時(shí)器左右(只是在屏幕內(nèi)的cell 創(chuàng)建定時(shí)器)這個(gè)足以導(dǎo)致 性能下降
那么讓我們嘗試使用一個(gè)定時(shí)器來完成所有的倒計(jì)時(shí)操作,既然要往這個(gè)方向做棺亭,我們先來整理下思路
在這里虎眨,可能會(huì)遇到一個(gè)問題,獲取屏幕內(nèi)可見的cell的時(shí)候镶摘,并不知道當(dāng)前cell是那個(gè)嗽桩,對(duì)應(yīng)的需要的展示的倒計(jì)時(shí),怎么對(duì)應(yīng)上凄敢,那么我們可以給cellforindexpath 的方法給cell.tag = indexPath.row 通過 tag 標(biāo)簽 和時(shí)間數(shù)組的索引碌冶,對(duì)應(yīng)找出相應(yīng)的時(shí)間展示的倒計(jì)時(shí)
//定時(shí)器刷新倒計(jì)時(shí)
-(void)calTime
{
NSArray *cells = _tableView.visibleCells; //取出屏幕可見cell
for (UITableViewCell *cell in cells) {
cell.textLabel.text = [self getTimeStr:timeArr[cell.tag]];
}
}
//返回倒計(jì)時(shí)
-(NSString *)getTimeStr:(NSString *)fireStr
{
NSDateFormatter* formater = [[NSDateFormatter alloc] init];
[formater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate* fireDate = [formater dateFromString:fireStr];
NSDate *today = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *d = [calendar components:unitFlags fromDate:today toDate:fireDate options:0];//計(jì)算時(shí)間差
long hour = [d day] *24 + [d hour];
NSString *seconds;
NSString *minutes;
NSString *hours;
if([d second]<10)
seconds = [NSString stringWithFormat:@"0%ld",[d second]];
else
seconds = [NSString stringWithFormat:@"%ld",[d second]];
if([d minute]<10)
minutes = [NSString stringWithFormat:@"0%ld",[d minute]];
else
minutes = [NSString stringWithFormat:@"%ld",[d minute]];
if(hour < 10)
hours = [NSString stringWithFormat:@"0%ld", hour];
else
hours = [NSString stringWithFormat:@"%ld",hour];
return [NSString stringWithFormat:@" 倒計(jì)時(shí)%@:%@:%@", hours, minutes,seconds];
}
這里已經(jīng)將需要展示的倒計(jì)時(shí)正常展示出來了,那么還有什么可以優(yōu)化一下涝缝,我們還可以對(duì)定時(shí)器進(jìn)行簡單的優(yōu)化扑庞,就是在頁面消失的時(shí)候譬重,將定時(shí)器置空,停止輪詢罐氨,在頁面出現(xiàn)才可以輪詢臀规。
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if (_timer == nil) {
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(calTime) userInfo:nil repeats:YES];
}
}
-(void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
if(_timer)
{
_timer = nil;//關(guān)閉定時(shí)器,
}
}