前言
對于banner輪播圖,相信大家都會經常用到。自動循環播放的banner是很常見的UI組件。如何實現呢?下面就來給大家詳細介紹下,話不多說了,下面來一起學習學習吧。
1.實現思路
1.橫向滾動的banner。
2.自動循環播放banner。
3.特殊banner位的處理。
2.本文采用第二種:UICollectionView+UICollectionViewCell
關鍵代碼實現
2.1生成banner的特殊處理
- (void)setBannerList:(NSArray<KBannerItem *> *)bannerList { if (bannerList.count > 1) { NSMutableArray *itemList = [NSMutableArray arrayWithArray:bannerList]; [itemList insertObject:bannerList.lastObject atIndex:0]; [itemList addObject:bannerList.firstObject]; _bannerList = itemList; }else{ _bannerList = bannerList; } if (self.bannerList.count > 1) { self.bannerPageControl.numberOfPages = self.bannerList.count - 2; }else{ self.bannerPageControl.numberOfPages = 0; } self.noBannerImageView.hidden = self.bannerList.count > 0; self.bannerPageControl.currentPage = 0; [self.collectionView reloadData]; self.collectionView.contentOffset = CGPointMake(CGRectGetWidth(self.collectionView.frame), 0);}
2.2 banner自動循環播放觸發的事件
- (void)handleBannerChangeEvent:(id)sender { if (_bannerPageControl.numberOfPages <= 1) { return; } NSInteger page = _bannerPageControl.currentPage + 1; [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:page + 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionRight animated:YES];}
2.3開啟自動播放或關閉自動播放bannner。
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { self.countTimer.isOpen = NO;}- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate { self.countTimer.isOpen = YES;}
2.4.滑動時的特殊處理。
- (void)scrollViewDidScroll:(UIScrollView *)scrollView { if (_bannerList.count <=1) { return; } CGFloat width = CGRectGetWidth(scrollView.frame); NSInteger currentPage = scrollView.contentOffset.x / width; if (currentPage == 0) { if (scrollView.contentOffset.x < 0) { [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:_bannerList.count - 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionRight animated:NO]; self.bannerPageControl.currentPage = _bannerList.count - 2; }else{ [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionRight animated:NO]; self.bannerPageControl.currentPage = 0; } }else if (currentPage == _bannerList.count - 1) { self.bannerPageControl.currentPage = 0; [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionRight animated:NO]; }else{ self.bannerPageControl.currentPage = currentPage - 1; }}
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答