无疑是重写flowlayout
import UIKit
class CustomFlowLayout: UICollectionViewFlowLayout {
/// 行间距
let RowSpace:CGFloat = 6
/// 列间距
let CollSpace:CGFloat = 6
/// 每页每行多少列
var numColl:Int = 4
/// 每页行数
var numRow:Int = 2
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func getMyPageNum()->Int {
if let collectionView = self.collectionView {
let pageNums = self.numRow * self.numColl
if let count = collectionView.dataSource?.collectionView(collectionView, numberOfItemsInSection: 0) {
/// 余数
let a = count%pageNums
/// 商数
let b = count/pageNums
/// 页数
var c:Int = b
if a > 0 {
c = b + 1
}
return c
}
return 1
}
return 1
}
/// 内容大小
override var collectionViewContentSize: CGSize{
if let collectionView = self.collectionView {
let page = self.getMyPageNum()
let width:CGFloat = CGFloat(page) * collectionView.bounds.size.width
return CGSize.init(width: width, height: collectionView.bounds.size.height)
}
return CGSize.zero
}
/// 自定义布局必须YES
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
func getItemSize() -> CGSize {
if let collectionView = self.collectionView {
let itemW = (collectionView.bounds.size.width - CollSpace * CGFloat(self.numColl - 1) ) / CGFloat(self.numColl)
let itemH = (collectionView.bounds.size.height - RowSpace * CGFloat(self.numRow - 1)) / CGFloat(self.numRow)
return CGSize.init(width: itemW, height: itemH)
}
return CGSize.init(width: 20, height: 20)
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if let item = super.layoutAttributesForItem(at: indexPath) {
if let collectionView = self.collectionView {
let pageNums = self.numRow * self.numColl
let itemW = self.getItemSize().width
let itemH = self.getItemSize().height
/// 页号 从零开始
let c = indexPath.row/pageNums
/// 余数
let a = indexPath.row%pageNums
var rect = item.frame
rect.size.width = itemW
rect.size.height = itemH
rect.origin.x = CGFloat(a%self.numColl) * (itemW + CollSpace) + collectionView.bounds.size.width * CGFloat(c)
let row = (indexPath.row/self.numColl)%self.numRow
rect.origin.y = CGFloat(row) * (itemH + RowSpace)
print("rect=== \(rect) \(indexPath.row)")
item.frame = rect
}
return item
}
return nil
}
override func prepare() {
super.prepare()
self.scrollDirection = .horizontal
self.itemSize = self.getItemSize()
self.sectionInset = .zero
self.minimumLineSpacing = self.RowSpace
self.minimumInteritemSpacing = self.CollSpace
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
if let array = super.layoutAttributesForElements(in: rect) {
var attributes:[UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]();
for (index,item) in array.enumerated() {
if let model = self.layoutAttributesForItem(at: item.indexPath) {
attributes.append(model)
}
}
return attributes
}
return nil
}
}
网友评论