iOScollectionView广告无限滚动(Swift实现)
今天公司里的实习生跑过来问我一般App上广告的无限滚动是怎么实现的,刚好很久没写博客了,就决定写下了,尽量帮助那些处于刚学iOS的程序猿.
做一个小demo,大概实现效果如下图所示:

基本实现思路:
1. 在你需要放置无限滚动展示数据的地方把他的数据,在原本的基础上把你要展示的数据扩大三倍.(当然扩大两倍也是可以的,三倍的话,比较好演示)
// MARK: - 设置数据源
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// print(self.arrayM.count)
return self.arrayM.count *
}
2.当在定时器的作用下,或者在拖动情况存下滚动到第八个时候,设置此时的collectionView.contentOffset.x等于滚动到第三个cell的contentOffset.x

if collectionView.contentOffset.x == CGFloat( * self.arrayM.count - ) * self.collectionView.bounds.width {
self.collectionView.contentOffset.x = CGFloat(self.arrayM.count - ) * self.collectionView.bounds.width
}
3.当拖动到第0个cell时,设置此时的collectionView.contentOffset.x等于第六个cell的contentOffset.x

if collectionView.contentOffset.x == {
self.collectionView.contentOffset.x = CGFloat( * self.arrayM.count - ) * self.collectionView.bounds.width
}
代码如下:
我在代码中用到5张照片,所以应该一共有15个cell
import UIKit
class ViewController: UIViewController ,UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
var timer : Timer?
var arrayM : [BOModel] = [] {
didSet {
self.collectionView.reloadData()
}
}
static let CellID = "cell"
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.dataSource = self
self.collectionView.delegate = self
// 加载数据
loadData()
self.collectionView.register(UINib.init(nibName: "BOCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: ViewController.CellID)
//设置collextionView
setupCollectionView()
// 开启定时器
starTimer()
}
/// 从polist中加载数据
func loadData() {
let stemp: NSArray = NSArray(contentsOfFile: Bundle.main.path(forResource: "shops.plist", ofType: nil)!)!
for dict in stemp {
let model = BOModel.init(dict: dict as! [String : Any])
self.arrayM.append(model)
}
}
/// 设置cellection的布局方式
///
/// - Returns: 一个布局类型
func setupCollectionFlowlayout() -> (UICollectionViewFlowLayout) {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.itemSize = self.collectionView.bounds.size
flowLayout.minimumLineSpacing =
flowLayout.minimumInteritemSpacing =
flowLayout.scrollDirection = .horizontal
flowLayout.sectionInset = UIEdgeInsetsMake(, , , )
return flowLayout
}
/// 设置collectionVIew
func setupCollectionView() -> () {
self.collectionView.collectionViewLayout = self.setupCollectionFlowlayout()
self.collectionView.showsVerticalScrollIndicator = false
self.collectionView.showsHorizontalScrollIndicator = false
self.collectionView.isPagingEnabled = true
}
// MARK: - 设置数据源
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// print(self.arrayM.count)
return self.arrayM.count *
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: ViewController.CellID, for: indexPath) as! BOCollectionViewCell
cell.model = self.arrayM[indexPath.row % self.arrayM.count]
return cell
}
// MARK: - 实现代理方法
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
//contentOffset.x == 0 时,重新设置contentOffset.x的值
if collectionView.contentOffset.x == {
self.collectionView.contentOffset.x = CGFloat( * self.arrayM.count - ) * self.collectionView.bounds.width
}
//当到达最后一个cell时,重新设置contentOffset.x的值
if collectionView.contentOffset.x == CGFloat( * self.arrayM.count - ) * self.collectionView.bounds.width {
self.collectionView.contentOffset.x = CGFloat(self.arrayM.count - ) * self.collectionView.bounds.width
}
}
/// 开启定时器
func starTimer () {
let timer = Timer.init(timeInterval: , target: self, selector: #selector(ViewController.nextPage), userInfo: nil, repeats: true)
// 这一句代码涉及到runloop 和 主线程的知识,则在界面上不能执行其他的UI操作
RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
self.timer = timer
}
/// 在1秒后,自动跳转到下一页
func nextPage() {
// 如果到达最后一个,则变成第四个
if collectionView.contentOffset.x == CGFloat( * self.arrayM.count - ) * self.collectionView.bounds.width {
self.collectionView.contentOffset.x = CGFloat(self.arrayM.count - ) * self.collectionView.bounds.width
}else {
// 每过一秒,contentOffset.x增加一个cell的宽度
self.collectionView.contentOffset.x += self.collectionView.bounds.size.width
}
}
/// 当collectionView开始拖动的时候,取消定时器
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.timer?.invalidate()
self.timer = nil
}
/// 当用户停止拖动的时候,开启定时器
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
starTimer()
}
}
plist文件如下图所示:
用到的字典转模型因为比较简单的转换,就自己写了个:
import UIKit
class BOCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
var model : BOModel? {
didSet {
guard let image = UIImage.init(named: (model?.name)!) else {
return
}
self.imageView.image = image
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
}
自定义collectionViewCell类中的内容:
import UIKit
class BOCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
var model : BOModel? {
didSet {
guard let image = UIImage.init(named: (model?.name)!) else {
return
}
self.imageView.image = image
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
}
附: 其实这种方法比较实现无限滚动,利用了一点小技巧,用电脑测试的时候可能有一点缺陷.
iOScollectionView广告无限滚动(Swift实现)的更多相关文章
- iOS开发:一个无限滚动自动播放图片的Demo(Swift语言编码)
很久以前就想写这么一个无限滚动的Demo了,最近学习了下Swift,手中没有可以用来练手的Demo,所以才将它实现了. Github地址(由于使用了UIView+AutoLayout第三方进行布局,所 ...
- iOS swift版本无限滚动轮播图
之前写过oc版本的无限滚动轮播图,现在来一个swift版本全部使用snapKit布局,数字还是pageConrrol样式可选 enum typeStyle: Int { case pageContro ...
- UIScrollView实现图片轮播器的无限滚动
简介 在现在的一些App中常常见到图片轮播器,一般用于展示广告.新闻等数据,在iOS内并没有现成的控件直接实现这种功能,但是通过UIScrollView的允许分页设置,可以实现滚动轮播的功能. 轮播原 ...
- Infinite Scroll - jQuery & WP 无限滚动插件
无限滚动(Infinite Scroll)也称为自动分页.滚动分页和无限分页.常用在图片.文章或其它列表形式的网页中,用来在滚动网页的时候自动加载下一页的内容.Infinite Scroll 这款 ...
- [Unity3D插件]2dtoolkit系列二 动画精灵的创建以及背景图的无限滚动
经过昨天2dtoolkit系列教程一的推出,感觉对新手还有有一定的启发作用,引导学习使用unity 2dToolKit插件的使用过程,今天继续系列二——动画精灵的创建,以及背景图的无限循环滚动,在群里 ...
- 基于HTML5+CSS3的图片旋转、无限滚动、文字跳动特效
本文分享几种基于HTML5+CSS3实现的一些动画特效:图片旋转.无限滚动.文字跳动;实现起来均比较容易,动手来试试! 一.图片旋转 效果图如下: 这个效果实现起来其实并不困难.代码清单如下: < ...
- LoopBar – Tap酒吧与无限滚动
相约 LoopBar – 标签栏与无限滚动为Android由Cleveroad 在Cleveroad我们最近认识到通过使用任何一个应用程序类别的导航,导航面板是很无聊和琐碎.这就是为什么我们的设计师的 ...
- Android 高级UI设计笔记09:Android如何实现无限滚动列表
ListView和GridView已经成为原生的Android应用实现中两个最流行的设计模式.目前,这些模式被大量的开发者使用,主要是因为他们是简单而直接的实现,同时他们提供了一个良好,整洁的用户体验 ...
- 无限滚动 --demo
<!DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content=&q ...
随机推荐
- [APUE]进程控制(上)
一.进程标识 进程ID 0是调度进程,常常被称为交换进程(swapper).该进程并不执行任何磁盘上的程序--它是内核的一部分,因此也被称为系统进程.进程ID 1是init进程,在自举(bootstr ...
- nodejs进阶(3)—路由处理
1. url.parse(url)解析 该方法将一个URL字符串转换成对象并返回. url.parse(urlStr, [parseQueryString], [slashesDenoteHost]) ...
- PHP搭建大文件切割分块上传功能
背景 在网站开发中,文件上传是很常见的一个功能.相信很多人都会遇到这种情况,想传一个文件上去,然后网页提示"该文件过大".因为一般情况下,我们都需要对上传的文件大小做限制,防止出现 ...
- [PHP内核探索]PHP中的哈希表
在PHP内核中,其中一个很重要的数据结构就是HashTable.我们常用的数组,在内核中就是用HashTable来实现.那么,PHP的HashTable是怎么实现的呢?最近在看HashTable的数据 ...
- .NET Core的日志[4]:将日志写入EventLog
面向Windows的编程人员应该不会对Event Log感到陌生,以至于很多人提到日志,首先想到的就是EventLog.EventLog不仅仅记录了Windows系统自身针对各种事件的日志,我们的应用 ...
- .NET CoreCLR开发人员指南(上)
1.为什么每一个CLR开发人员都需要读这篇文章 和所有的其他的大型代码库相比,CLR代码库有很多而且比较成熟的代码调试工具去检测BUG.对于程序员来说,理解这些规则和习惯写法非常的重要. 这篇文章让所 ...
- 对百度WebUploader开源上传控件的二次封装,精简前端代码(两句代码搞定上传)
前言 首先声明一下,我这个是对WebUploader开源上传控件的二次封装,底层还是WebUploader实现的,只是为了更简洁的使用他而已. 下面先介绍一下WebUploader 简介: WebUp ...
- python 数据类型 ---文件一
1.文件的操作流程: 打开(open), 操作(read,write), 关闭(close) 下面分别用三种方式打开文件,r,w,a 模式 . "a"模式将不会覆盖原来的文件内容, ...
- css3更改input单选和多选的样式
在项目开发中我们经常会遇到需要更改input单选和多选样式的情况,今天就给大家介绍一种简单改变input单选和多选样式的办法. 在这之前先简单介绍一下:before伪类 :before 选择器向选定的 ...
- Ajax部分
Ajax的概念 AJAX即"Asynchronous Javascript And XML"(异步JavaScript和XML),是一种用于创建快速动态网页的技术. 动态网页:是指 ...