iOS UICollectionView循环滚动的轮播界面

记录下自己项目中用到的循环轮播功能。

image.png

项目采用UICollectionView来实现滚动的功能,页面类似同花顺的股票详情切换,点击列表数据的时候展示左右切换按钮,来实现标题的滚动以及页面数据的重新请求。

@interface StockNavigationView () 

@property (weak, nonatomic) IBOutlet UIButton *thePreviousBtn;
@property (weak, nonatomic) IBOutlet UIButton *theNextBtn;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong) NSArray *dataAry;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, assign) NSInteger totalItemsCount;

@end

实现的思路是,通过加载比实际内容多的cell来形成左右无限循环滚动的效果,即self.totalItemsCount = self.dataAry.count * 100;

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.totalItemsCount;
}

因为加载了很多的cell,所以需要通过相应的算法来计算准确的index角标值。

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    StockNavigationCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"StockNavigationCell" forIndexPath:indexPath];
    long itemIndex = [self pageControlIndexWithCurrentCellIndex:indexPath.item];
    [cell em_displayWithID:self.dataAry[itemIndex]];

    return cell;
}

通过currentIndex方法计算出UICollectionView当前的偏移量,然后通过- (int)pageControlIndexWithCurrentCellIndex:(NSInteger)index;方法计算出在实际数组self.dataAry内的索引值。

- (int)pageControlIndexWithCurrentCellIndex:(NSInteger)index {
    return (int)index % self.dataAry.count;
}

- (int)currentIndex {
    if (_collectionView.frame.size.width == 0 || _collectionView.frame.size.height == 0) {
        return 0;
    }
    
    int index = 0;
    if (_flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
        index = (_collectionView.contentOffset.x + _flowLayout.itemSize.width * 0.5) / _flowLayout.itemSize.width;
    } else {
        index = (_collectionView.contentOffset.y + _flowLayout.itemSize.height * 0.5) / _flowLayout.itemSize.height;
    }
    
    return MAX(0, index);
}

然后添加上一页和下一页的方法

- (IBAction)thePreviousBtnClick:(id)sender {
    if (0 == _totalItemsCount) return;
    int currentIndex = [self currentIndex];
    int targetIndex = currentIndex - 1;
    [self scrollToIndex:targetIndex];
}

- (IBAction)theNextBtnClock:(id)sender {
    if (0 == _totalItemsCount) return;
    int currentIndex = [self currentIndex];
    int targetIndex = currentIndex + 1;
    [self scrollToIndex:targetIndex];
}

通过- (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated;方法来滚动到相应的位置。

- (void)scrollToIndex:(int)targetIndex {
    if (targetIndex >= _totalItemsCount) {
        targetIndex = _totalItemsCount * 0.5;
        int indexOnPageControl = [self pageControlIndexWithCurrentCellIndex:targetIndex];
        NSDictionary *dict = self.dataAry[indexOnPageControl];
        if (self.stockNavigationBlock) {
            self.stockNavigationBlock(dict[@"name"], dict[@"num"], dict[@"instrument"]);
        }

        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        return;
    }
    
    [UIView animateWithDuration:0.3 animations:^{
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    } completion:^(BOOL finished) {
        int indexOnPageControl = [self pageControlIndexWithCurrentCellIndex:targetIndex];
        NSDictionary *dict = self.dataAry[indexOnPageControl];
        if (self.stockNavigationBlock) {
            self.stockNavigationBlock(dict[@"name"], dict[@"num"], dict[@"instrument"]);
        }
    }];
//    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}

为了在UICollectionView左右手势滑动的方法中实现相应的功能,我们在- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;方法中实现了- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView;方法,达到了停止滚动后,都能产生响应。

// 滚动视图减速完成,滚动将停止时,调用该方法。一次有效滑动,只执行一次。
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self scrollViewDidEndScrollingAnimation:self.collectionView];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    int itemIndex = [self currentIndex];
    int indexOnPageControl = [self pageControlIndexWithCurrentCellIndex:itemIndex];
    NSDictionary *dict = self.dataAry[indexOnPageControl];
    if (self.stockNavigationBlock) {
        self.stockNavigationBlock(dict[@"name"], dict[@"num"], dict[@"instrument"]);
    }
}

最后,只需要在- (void)layoutSubviews;方法中,将self.collectionView滚动到居中的位置即可。其中self.index为传入数组的偏移量。

- (void)layoutSubviews {
    [super layoutSubviews];
    
    if (self.collectionView.contentOffset.x == 0 && _totalItemsCount) {
        int targetIndex = _totalItemsCount * 0.5;
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex + self.index inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
}

至此,一个简单循环滚动功能就完成了,如果有需要的话,还可以加上定时器等等等,当然了,这些都有现成的框架可以用。

本文中的代码,参考自SDCycleScrollView的源码。

你可能感兴趣的:(iOS UICollectionView循环滚动的轮播界面)