Автоматическая прокрутка ячеек Collectionview с использованием таймера

#objective-c #uicollectionview

#objective-c #uicollectionview

Вопрос:

Я пытаюсь автоматически прокручивать ячейки представления коллекции каждые 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 секунду.
кто-нибудь знает, в чем проблема?
Спасибо

Ответ №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];
}