如何每秒更新UICollectionViewCell的UILabel(swift)
我有一个UICollectionViewCell
与UILabel
显示两个date之间的日差。 我想每秒更新一次。 我曾尝试使用NSTimer
重新加载UICollectionview
的数据,但它使得用户界面非常慢。
我如何去实现这个? 谢谢。
您不会重新加载整个CollectionView,甚至不重新加载标签。
你有2个选项:
- 在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标签和标签设置为全局,这样很容易使用。
- (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; }
现在将计时器设置为viewWillAppear
- (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"); }
我希望这对你有所帮助,因为它在我身边工作的非常好,所以希望和你一样工作。