废话不多说,直接上代码
自定义一个SYitemViewLayout,继承UICollectionViewFlowLayout
mport UIKit
//根据需求设置列跟行
let kEmotionCellNumberOfOneRow = 3
let kEmotionCellRow = 2
class SYitemViewLayout: UICollectionViewFlowLayout {
// 保存所有item
fileprivate var attributesArr: [UICollectionViewLayoutAttributes] = []
// MARK:- 重新布局
override func prepare() {
super.prepare()
let itemWH: CGFloat = (kScreenWitdh - 30) / CGFloat(kEmotionCellNumberOfOneRow)
// 设置itemSize
itemSize = CGSize(width: itemWH, height: itemWH - 50)
minimumLineSpacing = 0
minimumInteritemSpacing = 0
scrollDirection = .horizontal
// 设置collectionView属性
collectionView?.isPagingEnabled = true
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.showsVerticalScrollIndicator = true
// let insertMargin = (collectionView!.bounds.height - 3 * itemWH) * 0.5
// collectionView?.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
var page = 0
let itemsCount = collectionView?.numberOfItems(inSection: 0) ?? 0
for itemIndex in 0..<itemsCount {
let indexPath = IndexPath(item: itemIndex, section: 0)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
page = itemIndex / (kEmotionCellNumberOfOneRow * kEmotionCellRow)
// 通过一系列计算, 得到x, y值
let x = itemSize.width * CGFloat(itemIndex % Int(kEmotionCellNumberOfOneRow)) + (CGFloat(page) * (kScreenWitdh - 30))
let y = itemSize.height * CGFloat((itemIndex - page * kEmotionCellRow * kEmotionCellNumberOfOneRow) / kEmotionCellNumberOfOneRow)
attributes.frame = CGRect(x: x, y: y, width: itemSize.width, height: itemSize.height)
// 把每一个新的属性保存起来
attributesArr.append(attributes)
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var rectAttributes: [UICollectionViewLayoutAttributes] = []
_ = attributesArr.map({
if rect.contains($0.frame) {
rectAttributes.append($0)
}
})
return rectAttributes
}
}
网友评论