水平自动滚动UICollectionviewcell

时间:2018-12-05 11:34:54

标签: ios objective-c uicollectionview uicollectionviewcell autoscroll

我正在尝试实现UICollectionView单元格的水平自动滚动。从第一个索引滚动到第二个索引之后,滚动停止并且NSTimer无效。下面是我实现的代码。我究竟做错了什么? 集合视图在tableviewcell内部。 UITableview --- UITableViewCell-第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];
}

1 个答案:

答案 0 :(得分:1)

对于NSTimer,将repeats:NO设置为TRUE 不要在滚动委托中添加和删除计时器。