15.自定义无限轮播View Cell
Collection来实现一个无线轮播的View
1.新建自定义的 View - Cell ,

继承自 UIView

2.继续创建针对Cell View 创建XIB文件,新建,选择View下一步

选择我们需要创建的Cell View 点击确定,即创建了针对该Cell View的XIB文件

2.2将Cell View 与 XIB文件进行关联

2.3修改XIB的Size改为Freeform,

2.4修改XIB的显示大小:

2.5先将这个View 注册到页面进行展示。

2.6 提供一个快速创建View 的类方法
// MARK:提供一个快速创建View的类方法
extension RecommenCycleView{
//声明XIB
classfuncRecommenCycleView() ->RecommenCycleView{
return Bundle.main.loadNibNamed("RecommenCycleView", owner:nil, options:nil)?.first as! RecommenCycleView
}
}

2.7 设置View 不跟随父控件的拉伸而拉伸
class RecommenCycleView:UIView{
override func awakeFromNib() {
super.awakeFromNib()
//MARK :设置该控件不随父控件的拉伸而拉伸
autoresizingMask=UIViewAutoresizing()
}
}

3.回到Controller ,懒加载定义一个 CycleView,为了能使cycleView能跟随页面滑动,需要注册到collectionView中
3.1定义cycleView控件的高度常量

3.2懒加载闭包创建cycleView,并定义Frame

3.3 为了让Cycleview能跟随页面滑动,需要将cycleView添加到collectionView中

3.4 设置collectionView的内边距

运行效果:

4.继续给CycleView增加collectionView来进展展示轮播
4.1在CycleView中拖入 collectionView 控件

4.2给拖入的collectionView进行约束

设置约束后

4.3 拖入一个pageController 到CollectionView上

4.4 修改pageController选中颜色和默认颜色

4.5设置约束

4.6运行查看效果
collectionview默认背景为白色

4.7 给collectionView设置数据源
选中collectionView 右键,连接数据源

4.8声明XIB控件属性

4.9 注册collectionView
定义一个Cell ID 常量
privatelet kCycleCellID ="kCycleCellID"
注册cell
// MARK:2.注册Cell,修改为使用XIB进行注册
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier:kCycleCellID)

5.0 遵循CollectionView 的数据源协议
随机设置了一个返回6组数据
//MARK:遵循collectionView的数据源协议
extension RecommenCycleView: UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 6
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleCellID, for: indexPath)
return cell
}
}

5.1为了能看到不同的效果,需要对CollectionView 的背景颜色进行一下设置。

5.2 运行查看效果:需要调整一下大小和间隔

5.3 设置collection布局
override func layoutSubviews() {
super.layoutSubviews()
// MARK: 设置collectionView 的layput布局
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
}

5.3 在XIB中设置其他的布局属性
5.3.1选中Collection View Flow layout 设置item之间的间距为0

5.3.2选中Collection View Flow layout设置滚动方向:水平滚动

5.3.3 选中Collection View 取消滚动条显示,勾选允许分页

运行查看效果:

小马哥23