引言: swift 轮播图原理
利用UICollectionView , cell0 , cell1 ,cell2 三个cell,
cell 每次滑完之后, 然后刷新数据, 都要再滚动到中间去(不需动画),
图片组: 要显示的图片数组
下标: 图片组的下表
数据源: CollectionView的数据源 (三条数据)
主要代码1:
datas 取图片组里的要显示的三条
var datas:[String]? {
var firstIndex = 0;
var secondIndex = 0
var thirdIndex = 0;
switch pictures.count {
case 0:
return []
case 1:
return []
default:
firstIndex = (self.index - 1) < 0 ? pictures.count - 1 : self.index - 1
secondIndex = self.index
thirdIndex = (self.index + 1) > pictures.count - 1 ? 0 : self.index + 1;
}
return [pictures[firstIndex] ,pictures[secondIndex] ,pictures[thirdIndex]];
}
var index: Int = 0 {
willSet {
//print("------------index:\(index)--------------")
}
didSet {
//print("------------index:\(index)--------------");
}
}
var pictures:[String] = [] {
didSet {
self.collectionV.scrollToItem(at: IndexPath(item: 1, section: 0), at: .left, animated: false)
}
}
主要代码2:
滚动的时候,拿正确的下表,并刷新UI,默认滚中间
func scrollViewDidScroll(_ scrollView: UIScrollView) {
var offset: CGFloat = 0
offset = scrollView.contentOffset.x
if offset >= self.collectionV.bounds.size.width * 2 {
if self.index == self.pictures.count - 1 {
self.index = 0
}
else {
self.index += 1
}
print("---------刷新:\(self.index)----------")
self.collectionV.reloadData();
self.collectionV.scrollToItem(at: IndexPath(item: 1, section: 0), at: .left, animated: false)
}
if offset <= 0 {
if self.index == 0 {
self.index = self.pictures.count - 1
}
else {
self.index -= 1
}
print("---------刷新:\(self.index)----------")
self.collectionV.reloadData()
self.collectionV.scrollToItem(at: IndexPath(item: 1, section: 0), at: .left, animated: false)
}
}
主要代码3:
UICollectionView 的代理
extension JBKSliderPictureView : UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: JBKSliderPictureCell = collectionView.dequeueReusableCell(withReuseIdentifier: "JBKSliderPictureCell", for: indexPath) as! JBKSliderPictureCell;
cell.nameLabel.text = "---(\(indexPath.item))---"
cell.imageV.image = UIImage(named: self.datas![indexPath.item]);
return cell;
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let index = self.index
print("-------------didSelectItemAt:\(index)---------------")
}
}