Я пытаюсь автоматически прокручивать ячейки представления коллекции каждые 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 секунд все идет не так, ячейки прокручиваются очень быстро, функция таймера вызывается примерно 10 или более раз за 1 секунду. кто-нибудь знает, где проблема? Спасибо
Удалите эту строку из метода cellForItemAtIndexPath
и используйте в методе viewDidLoad.
self.scrollingTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(startTimer:) userInfo:@{@"index" : [NSString stringWithFormat:@"%ld", (long)rowIndex]} repeats:YES];
функция таймера вызывается примерно 10 или более раз за 1 секунду
cellForItemAtIndexPath
метод вызывается несколько раз. И он каждый раз создает новый таймер. Если создать 10 таймеров, то ячейки будут анимироваться в 10 раз быстрее.
ИЛИ
Проверьте, запущен ли 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];
}