我试图每5秒自动滚动收集视图单元格,所以我创建了一个计时器并尝试了以下代码:
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
BannerCell *cell = [self.bannerCollectionView dequeueReusableCellWithReuseIdentifier:@"bannerCell" forIndexPath:indexPath];
//cell.isRoundImg = YES;
[cell fillCellWithBanner:self.banners[indexPath.row]];
NSInteger rowIndex = indexPath.row;
NSInteger numberOfRecords = self.banners.count -1;
if(rowIndex < numberOfRecords){
rowIndex = (rowIndex + 1);
}else {
rowIndex = 0;
}
self.scrollingTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(startTimer:) userInfo:@{@"index" : [NSString stringWithFormat:@"%ld", (long)rowIndex]} repeats:YES];
return cell;
}
-(void)startTimer:(NSTimer *)timer{
NSString *indexString = timer.userInfo[@"index"];
NSInteger indexRow = [indexString integerValue];
NSLog(@"%ld", (long)indexRow);
// [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
[self.bannerCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:indexRow inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
// } completion:nil];
}
当我启动该应用程序时,我可以正常工作,但是大约30秒后,一切都出了问题,单元格的滚动速度非常快,计时器功能在1秒钟内被调用了大约10次以上。 有人知道问题出在哪里吗? 谢谢
答案 0 :(得分:0)
从cellForItemAtIndexPath
方法中删除此行,并在viewDidLoad方法中使用
self.scrollingTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(startTimer:) userInfo:@{@"index" : [NSString stringWithFormat:@"%ld", (long)rowIndex]} repeats:YES];
timers函数在1秒内被调用了约10次以上
cellForItemAtIndexPath
方法被多次调用。并且每次都会创建一个新的计时器。如果创建了10个计时器,则这些单元的动画速度将提高10倍。
OR
在scrollingTimer
中检查cellForItemAtIndexPath
是否已经启动
if (!scrollingTimer.isValid) {
self.scrollingTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(startTimer:) userInfo:@{@"index" : [NSString stringWithFormat:@"%ld", (long)rowIndex]} repeats:YES];
}