我有一个UICollectionViewCell
和一个显示两个日期之间日期差的UILabel
。我想每秒钟更新一次。我曾尝试使用NSTimer
来重新加载UICollectionview
的数据,但这会使UI非常缓慢。
我该如何实现这一目标?谢谢
您不会为了更新标签而重新加载整个CollectionView甚至单个单元格。
您有两个选项:
- 在ViewController中编写一个NSTimer,然后只刷新可见单元格的内容。在ViewController中每秒钟安排一个重复计时器
当计时器被触发时,通过以下方法获得可见单元格,并仅获得显示时间的标签。
let visibleIndexPaths = tableview.indexPathsForVisibleRows
var visibleCellsArray: [UITableViewCell] = []
for currentIndextPath in visibleIndexPaths! {
// You now have visible cells in visibleCellsArray
visibleCellsArray.append(tableview.cellForRowAtIndexPath(currentIndextPath)!)
}
- 在每个单元格中安排一个1秒的重复计时器。当计时器被触发时,只需更新相应单元格的标签
首先设置为CollectionView hader,并声明一个hader标签和标签集为global,这样就很容易使用了
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
if (kind == UICollectionElementKindSectionHeader) {
Like = indexPath;
UICollectionReusableView *reusableview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
if (reusableview==nil) {
reusableview=[[UICollectionReusableView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
}
for (UILabel *lbl in reusableview.subviews)
{
if ([lbl isKindOfClass:[UILabel class]])
{
[lbl removeFromSuperview];
}
}
label2=[[UILabel alloc] initWithFrame:CGRectMake(label.frame.size.width + 40, 0, 140, 50)];
[reusableview removeFromSuperview];
label2.text= [NSString stringWithFormat:@"END %@",[self testDateComaparFunc:[[DealArr valueForKey:@"end_time"] objectAtIndex:indexPath.section]]];
label2.textColor = [UIColor whiteColor];
[reusableview addSubview:label2];
return reusableview;
}
return nil;
}
现在在视图中设置计时器WillAppear
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(runMethod) userInfo:nil repeats:YES];
}
设置计时器方法与标签文本中使用的方法相同
-(void)runMethod
{
label2.text= [NSString stringWithFormat:@"END %@",[self testDateComaparFunc:[[DealArr valueForKey:@"end_time"] objectAtIndex:Like.section]]];
NSLog(@"i'm calling");
}
我希望它对你们有帮助,因为它对我很有效,所以希望和你们一样有效。