Swift 使用CollectionView 实现图片轮播封装就是这样简单
前言: 这篇你可以学会自定义视图,创建collectionView,协议的使用,定时器;
先上Demo:Github上封装好的下载即用, 好用请Star Thanks
首先新建一个继承于UIView的视图, 且用collectionView实现所以需要签订两个协议代码如下:
let sectionNum: Int = 100 // 区的数量
let width = UIScreen.mainScreen().bounds.size.width // 屏幕宽度
let height = UIScreen.mainScreen().bounds.size.width // 屏幕高度
// 因为要实现轮播图片可以点击定义一个协议
// 协议
protocol XTCycleViewDelegate {
func didSelectIndexCollectionViewCell(index: Int)->Void
}
class XTCycleScrollView: UIView, UICollectionViewDelegate, UICollectionViewDataSource{
使用到的变量以及创建视图
var delegate: XTCycleViewDelegate?
var cycleCollectionView: UICollectionView?
var images = NSMutableArray()
var pageControl = UIPageControl()
var flowlayout = UICollectionViewFlowLayout()
var timer = NSTimer()
override init(frame: CGRect) {
super.init(frame: frame)
self.createSubviews(frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
布局必要的UI以及创建定时器
func createSubviews(frame: CGRect){
cycleCollectionView = UICollectionView.init(frame: CGRectMake(0, 0, frame.size.width, frame.size.height), collectionViewLayout: flowlayout)
flowlayout.itemSize = CGSizeMake(frame.size.width, frame.size.height);
flowlayout.minimumInteritemSpacing = 0;
flowlayout.minimumLineSpacing = 0;
flowlayout.scrollDirection = UICollectionViewScrollDirection.Horizontal;
cycleCollectionView!.backgroundColor = UIColor.lightGrayColor()
cycleCollectionView!.pagingEnabled = true
cycleCollectionView!.dataSource = self
cycleCollectionView!.delegate = self
cycleCollectionView!.showsHorizontalScrollIndicator = false
cycleCollectionView!.showsVerticalScrollIndicator = false
cycleCollectionView!.registerClass(ZJCustomCycleCell.self, forCellWithReuseIdentifier: "cellId")
self.addSubview(cycleCollectionView!)
pageControl = UIPageControl.init(frame: CGRectMake(0, 0, frame.size.width / 2, 30))
pageControl.center = CGPointMake(frame.size.width / 2, frame.size.height - 20);
self.addSubview(pageControl);
self.addTimer()
}
定时器初始化
func addTimer(){
let timer1 = NSTimer.init(timeInterval: 2, target: self, selector: "nextPageView", userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(timer1, forMode: NSRunLoopCommonModes)
timer = timer1
}
销毁定时器
func removeTimer(){
self.timer.invalidate()
}
实现循环滚动
func returnIndexPath()->NSIndexPath{
var currentIndexPath = cycleCollectionView!.indexPathsForVisibleItems().last
currentIndexPath = NSIndexPath.init(forRow: (currentIndexPath?.row)!, inSection: sectionNum / 2)
cycleCollectionView!.scrollToItemAtIndexPath(currentIndexPath!, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
return currentIndexPath!;
}
func nextPageView(){
let indexPath = self.returnIndexPath()
var item = indexPath.row + 1;
var section = indexPath.section;
if item == images.count {
item = 0
section++
}
self.pageControl.currentPage = item;
let nextIndexPath = NSIndexPath.init(forRow: item, inSection: section)
cycleCollectionView!.scrollToItemAtIndexPath(nextIndexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
}
collectionView Delegate
// 重用池
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// 这里使用的自定义cell, 下面会贴出自定义cell代码
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellId", forIndexPath: indexPath) as! ZJCustomCycleCell
// 这个Label实现显示数字,表示是第几张图片
cell.labelTitle.text = NSString(format: "%d", indexPath.row) as String
// 这里是图片赋值
let url:String = self.images[indexPath.row] as! String
// 这里我使用的是一个赋值图片的三方库,看自己喜好,为方便我没有自己写
cell.imageView.hnk_setImageFromURL(NSURL.init(string: url)!)
return cell
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return sectionNum
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// 在这里给出了pageControl的数量
pageControl.numberOfPages = images.count
return images.count
}
// 重新添加定时器
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.addTimer()
}
// 手动滑动的时候销毁定时器
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
self.removeTimer()
}
设置当前的pagecontrol
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let page = (Int(scrollView.contentOffset.x) / Int(width)) % images.count
pageControl.currentPage = page
}
点击方法
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.delegate?.didSelectIndexCollectionViewCell(indexPath.row)
}
下面是我在自定义cell中的代码
var urlImage: String = ""
var imageView = UIImageView()
var labelTitle = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
self.createSubviews(frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func createSubviews(frame: CGRect){
imageView = UIImageView.init(frame: CGRectMake(0, 0, frame.size.width, frame.size.height))
self.contentView.addSubview(imageView)
labelTitle = UILabel.init(frame: CGRectMake(10, 10, 30, 30))
imageView.addSubview(labelTitle)
}
封装基本完成了, 下面看看如何使用
// 创建
let cycle = XTCycleScrollView.init(frame: CGRectMake(0, 70, width, 175))
// 要实现点击需要制定代理人
cycle.delegate = self;
// 图片链接数组
let images: NSMutableArray = ["", "", "", ""]
// 数组赋值
cycle.images = images
self.view.addSubview(cycle)
实现代理方法
func didSelectIndexCollectionViewCell(index: Int) {
print("\\(index)")
}
总结: 这样就实现了简单的图片轮播效果,并且带有点击方法, 都看到这里就点个赞吧. 哈哈
原文链接:http://www.jianshu.com/p/f5fa66699a96
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
Swift 使用CollectionView 实现图片轮播封装就是这样简单的更多相关文章
- Android 图片轮播(最简单的)
布局文件 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android ...
- swift 自定义图片轮播视图
Swift封装图片轮播视图: import UIKit class XHAdLoopView: UIView { private var pageControl : UIPageControl? pr ...
- swift:创建滚动视图的图片轮播器
用swift创建图片轮播器和用OC创建的方式是一样的,都主要用到UIScrollView和UIImageview这两个控件,有几张图片,就将滚动视图的内容区域大小设置为每一张图片的大小乘以张数即可.然 ...
- 如何将angular-ui的图片轮播组件封装成一个指令
在项目开发中我们经常会遇到图片轮播的功能点: 如果我们开发人员自己原生手写,将会花费很多的时间,最终得不偿失. 接下来就详细说说如何使用angular-ui发热图片轮播模块,并且将它写成一个指令(便于 ...
- 基于ionic框架封装一个图片轮播指令的几点
在这里我想在项目中封装一个图片轮播的指令 (本项目使用的是ionic框架) 1)定义指令 define(['app'],function(myapp){ myapp.directive('myslid ...
- 如何将angular-ui-bootstrap的图片轮播组件封装成一个指令
在项目开发中我们经常会遇到图片轮播的功能点: 如果我们开发人员自己原生手写,将会花费很多的时间,最终得不偿失. 接下来就详细说说如何使用angular-ui发热图片轮播模块,并且将它写成一个指令(便于 ...
- iOS开发项目实战——Swift实现图片轮播与浏览
近期開始开发一个新的iOS应用,自己决定使用Swift.进行了几天之后,发现了一个非常严峻的问题.那就是无论是书籍,还是网络资源,关于Swift的实在是太少了,随便一搜全都是OC实现某某某功能.就算是 ...
- UIScrollView实现图片轮播器及其无限循环效果
图片轮播器: 一.实现效果 实现图片的自动轮播 二.实现代码 storyboard中布局 代码: 1 #import "YYViewController.h" ...
- ios之无限 自动 图片轮播器的实现
比较之前发布的手动无限图片轮播器进行了改进.实现了自动无限轮播的功能.比较适合团购标题分类下面的轮播器功能. 实现思路: * 开启一个定时器,把操作放入消息循环池.每隔一定时间,操作执行一次. * 注 ...
随机推荐
- [读行者][学习LinqExpression和Reflection(Emit)]阅读TypeBuilderSample之ExampleFromTheArticle
前言 关于”读行者“ 俗语有云:"读万卷书,行万里路“.多读一些优秀代码,不仅可以锻炼我们读代码的能力(便于维护或相互交流),还可以吸取很多我们成长所需的知识点.多读,才能开阔我们的眼界,才 ...
- Asp.Net Web API开发微信后台
如果说用Asp.Net开发微信后台是非主流,那么Asp.Net Web API的微信后台绝对是不走寻常路. 需要说明的是,本人认为Asp.Net Web API在开发很多不同的请求方法的Restful ...
- Windows python 安装 nNumpy、Scipy、matplotlib模块
折腾了 很久,总结一些. 首先如果python 是64位,安装32位的numpy ,Scipy,或者matplotlib 模块. 会出现很多问题. 比如当你 在python 导入 Numpy 时,导入 ...
- 分布式架构--第一篇--项目拆分(maven命令生成多模块项目)
预览生成的项目结构: ying-yue-parent // 顶级总编译控制模块 ying-yue-lib // jar模块 ying-yue-model // 模型对象模块 ying-yue-dao ...
- 对C++中高内聚,低耦合原则的理解
1.C语言是面向过程的语言,采用模块化的设计思想,每个功能划分为一个模块,是以函数为单位的. 2.C++是面向对象的语言,采用类设计的思想,因此C++中的模块是以类为基本单位的. 高内聚,低耦合能够使 ...
- Google Volley: How to send a POST request with Json data?
sonObjectRequest actuallyaccepts JSONObject as body. From http://arnab.ch/blog/2013/08/asynchronous- ...
- STL之multiset
参见http://www.cplusplus.com/reference/set/multiset/ template < class T, ...
- 延迟加载 ERROR org.hibernate.LazyInitializationException:42 - could not initialize proxy - ...
no Session问题,即延迟加载 延迟加载的问题是指当我们调用完action中的某个方法,在jsp页面要显示我们想要的信息的时候,发现在dao中打开的session已经关闭了. 如下图,第一个箭头 ...
- Google Guava学习笔记——基础工具类Preconditions类的使用
Preconditions类是一组静态方法用来验证我们代码的状态.Preconditons类很重要,它能保证我们的代码按照我们期望的执行,如果不是我们期望的,我们会立即得到反馈是哪里出来问题,现在我们 ...
- BZOJ2879 [Noi2012]美食节
AC通道:http://www.lydsy.com/JudgeOnline/problem.php?id=2879 这题codevs上也有,不过数据不同:http://codevs.cn/proble ...