iOS UITableView中CELL新增計時器實現自動刪除的問題
最近在做一個“搶單”的功能,利用tableview來進行載入每一個單子上的資料,每個單子有60秒的生命週期。過了生命週期後會自動的刪除cell.
我們都知道要刪除cell,不僅需要[cellremoveFromSuperview];而且還需要刪除資料來源。但是由於計時器的使用,刪除資料來源的重新載入的時候又會遇到新的問題。
此時手動刪除cell能比較簡單地實現
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
FLAskTheLawerTableViewCell *cell= [self.contentViewcellForRowAtIndexPath:indexPath];
if ([cell.timeLable.text isEqualToString:@"0"]){
returnUITableViewCellEditingStyleDelete;
}else{
returnUITableViewCellEditingStyleNone;
}
}
//刪除計時到0得cell
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle
{
if (tableView == self.contentView){
if (editingStyle==UITableViewCellEditingStyleDelete){
//獲取選中刪除行索引值
NSInteger row = [indexPath row];
NSLog(@"獲取選中刪除行索引值 -------- %d",[indexPath row]);
//通過獲取的索引值刪除陣列中的值
[self.dataArray removeObjectAtIndex:row];
FLAskTheLawerTableViewCell *cell= [self.contentView cellForRowAtIndexPath:indexPath];
//刪除單元格的某一行時,在用動畫效果實現刪除過程
[self.contentViewdeleteRowsAtIndexPaths:[NSArrayarrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
//重新建立已刪除的cell上的計時器效果
cell.timer = 61;
cell.timeLable.text = [NSString stringWithFormat:@"%d",cell.timer];
self.cellTimer = [NSTimerscheduledTimerWithTimeInterval:1target:selfselector:@selector(getTime:) userInfo:cell repeats:YES];
[self.cellTimer timeInterval];
cell.btn.userInteractionEnabled = YES;
[cell.btnsetBackgroundColor:[UIColorcolorWithRed:0.08627green:0.37647blue:0.76471alpha:1]];
}
}
} 一定要特別注意手動刪除cell也會面臨問題當你再次新增cell與你原先刪除的cell是同一個indexpth時你會發現出現奇怪的問題,這個時候你就要考慮為什麼會出現。(資料來源重現以及cell沒有徹底delloc的原因)
再次回到計時器自動刪除cell,此時面臨最大的問題就是在即時結束之後怎麼刪除相應的資料來源。我是自定義cell。根據自己的情況獲取資料來源,因為如果只是[selfremoveFromSuperview]的話,你會發現滑動tableview時會出現重現問題。建議此時好好研究tableview中的代理方法。我們平時用的總是那幾個,其實很多在特殊情況下可以解決特殊問題。比如此時就可以用
-(void)tableView:(UITableView *)tableView
willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath {};來解決