需求: 固定高度的區(qū)域, 里面左右分頁顯示多個圖標(biāo), 每頁從左往右排列, 排滿后從上往下排, 這一頁排滿后排下一頁.參照oc的實現(xiàn)方式
我們很容易想到利用UICollectionView來實現(xiàn), 設(shè)置UICollectionViewFlowLayout, 然后設(shè)置為橫向.代碼如下:
fileprivate lazy var collectionView: UICollectionView = { [unowned self] in
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
// layout.rowCount = 2
// layout.itemCountPerRow = 3
layout.itemSize = CGSize(width: self.zs_width / 3.0, height: self.zs_width / 3.0 + 60.0)
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.frame = CGRect(x: 0, y: 0, width: self.zs_width, height: self.zs_height - 20.0)
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CELLID")
collectionView.isPagingEnabled = true
return collectionView
}()
這段代碼實現(xiàn)的效果:
怎么實現(xiàn)上述效果呢?
- 可以用大cell包含5個小圖標(biāo)來實現(xiàn)(這樣就比較復(fù)雜)
- 重寫UICollectionViewFlowLayout
這里我用重寫UICollectionViewFlowLayout實現(xiàn)
思路: 獲取collectionView所有cell的屬性, 然后進(jìn)行indexpath的計算, 用新計算出的indexPath替換原有的indexPath.
1.聲明屬性
/** 一行中cell的個數(shù)*/
public var itemCountPerRow: Int!
/** 一頁顯示多少行*/
public var rowCount: Int!
/** 存儲collectionView上cell的屬性*/
fileprivate var allAttributes: [UICollectionViewLayoutAttributes] = []
2.獲取所有cell的屬性
override func prepare() {
super.prepare()
let count = self.collectionView?.numberOfItems(inSection: 0) ?? 0
for i in 0..<count {
let indexPath = NSIndexPath(item: i, section: 0)
let attributes = self.layoutAttributesForItem(at: indexPath as IndexPath)
allAttributes.append(attributes!)
}
}
3.交換indexPath
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
var item = indexPath.item
var x = 0
var y = 0
self.targetPosition(item: item, x: &x, y: &y)
item = originItem(x, y: y)
let newIndexPath = NSIndexPath(item: item, section: 0)
let theNewAttr = super.layoutAttributesForItem(at: newIndexPath as IndexPath)
theNewAttr?.indexPath = indexPath
return theNewAttr
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let attributes = super.layoutAttributesForElements(in: rect)
var tmp: [UICollectionViewLayoutAttributes] = []
for attr in attributes! {
for attr2 in self.allAttributes {
if attr.indexPath.item == attr2.indexPath.item {
tmp.append(attr2)
break
}
}
}
return tmp
}
//根據(jù)item計算出目標(biāo)item的偏移量
//x 橫向偏移 y 豎向偏移
fileprivate func targetPosition(item: Int, x: inout Int, y: inout Int) {
let page = item / (self.itemCountPerRow * self.rowCount)
x = item % self.itemCountPerRow + page * self.itemCountPerRow
y = item / self.itemCountPerRow - page * self.rowCount
}
//根據(jù)偏移量計算item
fileprivate func originItem(_ x: Int, y: Int) -> Int {
let item = x * self.rowCount + y
return item
}