问题
I have a UICollectionViewCell
with a UILabel
showing the day difference between two dates. I want to update it every second. I have tried using NSTimer
to reload the data of the UICollectionview
, but it makes the UI very slow.
How do I go about achieving this? Thanks.
回答1:
You do not reload the whole CollectionView or even the individual cells just to update the label.
You have 2 options:
- Write a NSTimer in the ViewController and just refresh the content of the visible cells. Schedule a repeating timer in ViewController for every second.
When the timer is triggered, then obtain the visible cells by the following method and obtain just the label displaying the time.
let visibleIndexPaths = tableview.indexPathsForVisibleRows
var visibleCellsArray: [UITableViewCell] = []
for currentIndextPath in visibleIndexPaths! {
// You now have visible cells in visibleCellsArray
visibleCellsArray.append(tableview.cellForRowAtIndexPath(currentIndextPath)!)
}
- Schedule a 1 second repeating timer in each cell. When the timer is triggered, just update the label of the respective cell.
回答2:
First you set to CollectionView hader and declare one hader label and label set to global so it's easy to use.
- (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;
}
Now Set Timer in viewWillAppear
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(runMethod) userInfo:nil repeats:YES];
}
Set the Timer Method Same as you use into Label Text
-(void)runMethod
{
label2.text= [NSString stringWithFormat:@"END %@",[self testDateComaparFunc:[[DealArr valueForKey:@"end_time"] objectAtIndex:Like.section]]];
NSLog(@"i'm calling");
}
i hope it's help you because it's working on my side very well so hope same working as yours.
来源:https://stackoverflow.com/questions/38451793/how-to-update-uicollectionviewcells-uilabel-every-second-swift