iOS 用UICollectionView來實現自動輪播

  • 使用場景:自定義tableView的headerView,headerView實現了自動輪播

屬性和遵守的協議

[@interface](https://my.oschina.net/u/996807) CustomHeaderView ()<UICollectionViewDelegateFlowLayout, UICollectionViewDataSource>

[@property](https://my.oschina.net/property) (nonatomic, weak) UICollectionView *collectionView;

[@property](https://my.oschina.net/property) (nonatomic, strong) UIPageControl *pageControl;

[@property](https://my.oschina.net/property) (nonatomic, strong) NSTimer *timer;

[@end](https://my.oschina.net/u/567204)

cell的標識

static NSString *const CustomHeaderViewCellId = @"CustomHeaderViewCellId";

控制器的初始化

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // 設置UI
        [self setupUI];
        // 開啟定時器
        [self addLCTimer];
    }
    return self;
}

設置UI(高度180,五個item)

- (void)setupUI{
    self.backgroundColor = [UIColor whiteColor];
    
    // 創建collectionView
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 180);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 180) collectionViewLayout:flowLayout];
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.pagingEnabled = YES;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.bounces = NO;
    collectionView.contentSize = CGSizeMake(5 * collectionView.bounds.size.width, 0);
    [self addSubview:collectionView];
    self.collectionView = collectionView;
    
    // 注冊cell
    [collectionView registerNib:[UINib nibWithNibName:@"CustomHeaderViewCell" bundle:nil] forCellWithReuseIdentifier:CustomHeaderViewCellId];
    
    // pageControl
    UIPageControl *pageControl = [[UIPageControl alloc]init];
    pageControl.numberOfPages = 5;
    CGSize size = [pageControl sizeForNumberOfPages:5];
    pageControl.bounds = CGRectMake(0, 0, size.width, size.height);
    pageControl.center = CGPointMake(self.center.x, 130);
    [self addSubview:pageControl];
    self.pageControl = pageControl;
    
    self.pageControl.currentPage = 0;
}

數據源方法<UICollectionViewDataSource>

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 5;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CustomHeaderViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CustomHeaderViewCellId forIndexPath:indexPath];
    cell.model = self.modelsArray[indexPath.row];
    return cell;
}

代理方法<UICollectionViewDelegateFlowLatout>

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self removeLCTimer];
}

/** 當用戶停止的時候調用 */
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self addLCTimer];
}

/** 設置頁碼 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    int page = (int)(scrollView.contentOffset.x / scrollView.frame.size.width + 0.5) % 5;
    self.pageControl.currentPage = page;
}

添加定時器和刪除定時器

- (void)addLCTimer{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.timer = timer;
}

- (void)removeLCTimer{
    [self.timer invalidate];
    self.timer = nil;
}

nextPage(主要的算法)

- (void)nextPage {
    NSIndexPath *currentIndexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];
    
    NSIndexPath *currentIndexPathReset = [NSIndexPath indexPathForItem:currentIndexPath.item inSection:0];
    [self.collectionView scrollToItemAtIndexPath:currentIndexPathReset atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    
    NSInteger nextItem = currentIndexPathReset.item + 1;
    if (nextItem == 5) {
        nextItem = 0;
    }
    NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:0];
    
    [self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
}

設置數據源

- (void)setModelsArray:(NSArray<LCNewsModel *> *)modelsArray{
    _modelsArray = modelsArray;
}

完成以上方法就能實現一個用UICollectionView做的輪播系統,點擊跳轉的時間自己實現就可以了

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容