前言
对于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;
}
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对亿速云的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。