首页 > 解决方案 > 水平自动滚动 UICollectionviewcell

问题描述

我正在尝试实现 UICollectionView 单元格的水平自动滚动。滚动发生在从第一个索引到第二个索引之后它停止并且 NSTimer 无效。下面是我实现的代码。我究竟做错了什么?集合视图位于 tableviewcell 内。UITableview --- UITableViewCell -- Section 0 -- UI collectionview

 - (void)addTimer
{

    self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(nextPage) userInfo:nil repeats:NO];
    //    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(self.recCollectionView.frame.size.width, self.recCollectionView.frame.size.height);
}

- (void)nextPage
{
    @try
    {
        // 1.back to the middle of sections
        NSIndexPath *currentIndexPathReset = [self resetIndexPath];

        // 2.next position
        NSInteger nextItem = currentIndexPathReset.item + 1;
        NSInteger nextSection = currentIndexPathReset.section;
        if (nextItem == [[[self.schemeDataDictionary objectForKey:@"data"]objectForKey:delegate.tableString] count]) {
            nextItem = 0;
            nextSection++;
        }

        NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];

        // 3.scroll to next position
        [self.recCollectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
    }
    @finally {
        NSLog(@"finally");
    }
}
- (NSIndexPath *)resetIndexPath
{
    @try
    {
        // currentIndexPath
        NSIndexPath *currentIndexPath = [[self.recCollectionView indexPathsForVisibleItems] lastObject];
        // back to the middle of sections
        NSIndexPath *currentIndexPathReset = [NSIndexPath indexPathForItem:currentIndexPath.item inSection:0/2];
        [self.recCollectionView scrollToItemAtIndexPath:currentIndexPathReset atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        return currentIndexPathReset;
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
    }
    @finally {
        NSLog(@"finally");
    }   
}
- (void)removeTimer
{
    [self.timer invalidate];
    //self.timer = nil;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self removeTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self addTimer];
}

标签: iosobjective-cuicollectionviewuicollectionviewcellautoscroll

解决方案


对于NSTimer, 设置repeats:NOTRUE Don't add and remove timer in scroll delegates。


推荐阅读