最近遇到一个需求,一行单元格展示3个item,期间会穿插banner样式单元格,类似下图:
起初是想用UITableView来实现,但是需要定制展示3个item的cell,比较麻烦,因为后台给的数据就是一个装有各个item的数组,这样还得自己去把数据分组,反正比较麻烦,最后选择了用UICollectionView来实现,但是这样也是需要定制2种样式的item.我们知道tableview定制并且展示多种不同样式的cell是比较容易的, UICollectionView就有点不容易了.经过一番研究,找到解决方案,先记录如下,以备不时之需.
1.继承UICollectionViewFlowLayout定制一个布局类,重写几个核心方法
a.
override func prepare()
b.
override var collectionViewContentSize: CGSize
c.
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?
d.
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]?
有头视图的再加个这个方法
override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?
代码如下
import UIKit
let twoCellWidth: CGFloat = (UIScreen.main.bounds.width - 15 * 4) / 3
let twoCellHeight: CGFloat = twoCellWidth * 1.2
let oneCellWidth: CGFloat = UIScreen.main.bounds.width
let oneCellHeight: CGFloat = oneCellWidth * 0.5
let headerWidth: CGFloat = UIScreen.main.bounds.width
let headerHeight: CGFloat = 190
protocol CustomLayoutDataSource: NSObjectProtocol {
func treasureLayoutEachFrameForItemAtIndexPath(layout: CustomLayout,indexPath: IndexPath) -> CGRect
func collectionViewContentSize(layout: CustomLayout) -> CGSize
}
class CustomLayout: UICollectionViewFlowLayout {
weak var dataSource: CustomLayoutDataSource?
override func prepare() {
super.prepare()
}
override var collectionViewContentSize: CGSize {
get{
return dataSource?.collectionViewContentSize(layout: self) ?? CGSize.zero
}
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let attr = UICollectionViewLayoutAttributes.init(forCellWith: indexPath)
attr.frame = dataSource?.treasureLayoutEachFrameForItemAtIndexPath(layout: self, indexPath: indexPath) ?? CGRect.zero
return attr
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attrs = [UICollectionViewLayoutAttributes]()
for j in 0..<(collectionView?.numberOfSections)! {
let indexPath: IndexPath = IndexPath(item: 0, section: j)
attrs.append(layoutAttributesForSupplementaryView(ofKind: UICollectionElementKindSectionHeader, at: indexPath)!)
for i in 0..<(collectionView?.numberOfItems(inSection: j))! {
let indexPath = IndexPath(item: i, section: j)
attrs.append(layoutAttributesForItem(at: indexPath)!)
}
}
return attrs
}
override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if elementKind == UICollectionElementKindSectionHeader {
let attr = UICollectionViewLayoutAttributes.init(forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, with: indexPath)
attr.frame = CGRect(x: 0,y: 0,width: headerWidth,height: headerHeight)
return attr
}
return nil
}
}
定义一个数据源代理方法CustomLayoutDataSource
2.viewControllor初始化视图,注册item样式,头视图
let layout = CustomLayout()
layout.dataSource = self
layout.minimumLineSpacing = 15
layout.minimumInteritemSpacing = 15
collectionView = UICollectionView.init(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.lightGray
collectionView.dataSource = self
collectionView.delegate = self
view.addSubview(collectionView)
collectionView.register(CustomTwoCell.self, forCellWithReuseIdentifier: "twoCell")
collectionView.register(CustomOneCell.self, forCellWithReuseIdentifier: "oneCell")
collectionView.register(HeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")
3.实现相应的代理方法
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataArray.count
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionHeader {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header", for: indexPath) as! HeaderView
headerView.backgroundColor = UIColor.yellow
return headerView
}
return UICollectionReusableView()
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell: UICollectionViewCell
let dataDic: NSDictionary = dataArray[indexPath.row]
let type = dataDic["type"] as! Int
if type == 2 {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "twoCell", for: indexPath) as! CustomTwoCell
cell.backgroundColor = UIColor.green
}else{
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "oneCell", for: indexPath) as! CustomOneCell
cell.backgroundColor = UIColor.red
}
return cell
}
func collectionViewContentSize(layout: CustomLayout) -> CGSize {
var twoCellCount: Int = 0
var oneCellCount: Int = 0
for (_,dic) in dataArray.enumerated() {
let type: Int = dic["type"] as! Int
if type == 2{
twoCellCount += 1
}else{
oneCellCount += 1
}
}
var headerheight: CGFloat = 0
headerheight = headerHeight + layout.minimumLineSpacing
let twoCellHeightT: CGFloat = CGFloat(ceilf((Float(Float(twoCellCount) / 3)))) * twoCellHeight
let oneCellHeightT: CGFloat = CGFloat(oneCellCount) * oneCellHeight
let paddingHeightT: CGFloat = CGFloat(ceilf((Float(Float(twoCellCount) / 3))) + Float(oneCellCount)) * layout.minimumLineSpacing
let size = CGSize(width: view.bounds.width, height: twoCellHeightT + oneCellHeightT + paddingHeightT + headerheight)
return size
}
func treasureLayoutEachFrameForItemAtIndexPath(layout: CustomLayout, indexPath: IndexPath) -> CGRect {
var twoCellCount: Int = 0
var oneCellCount: Int = 0
var cellType: Int?
for (index, dic) in dataArray.enumerated() {
let type = dic["type"] as? Int
if indexPath.item == index {
cellType = type
break
}else if type == 2 {
twoCellCount += 1
}else{
oneCellCount += 1
}
}
var x: CGFloat = 15
var y: CGFloat = 0
var width: CGFloat = 0
var height: CGFloat = 0
let twoCellHeightT: CGFloat = CGFloat((twoCellCount / 3)) * twoCellHeight
let oneCellHeightT: CGFloat = CGFloat(oneCellCount) * oneCellHeight
let paddingHeightT: CGFloat = CGFloat((twoCellCount / 3) + oneCellCount) * layout.minimumLineSpacing
y = headerHeight + layout.minimumLineSpacing
if cellType == 2 {
width = twoCellWidth
height = twoCellHeight
if !(isCellOnLeftByTreasure(treasure: twoCellCount, oneCount: oneCellCount)) {
x = (width + layout.minimumInteritemSpacing) * CGFloat(indexCount) + layout.minimumInteritemSpacing;
}
y += (twoCellHeightT + oneCellHeightT + paddingHeightT)
}else{
x = 0
width = oneCellWidth
height = oneCellHeight
y += (twoCellHeightT + oneCellHeightT + paddingHeightT)
}
return CGRect(x: x,y: y,width: width,height: height)
}
func isCellOnLeftByTreasure(treasure: Int,oneCount: Int) -> Bool {
if (treasure + oneCount * 3) % 3 == 0 {
indexCount = 0
return true;
} else {
indexCount += 1
return false;
}
}
主要是在布局类的代理方法里计算坐标,高度,如代码所示
最后看下效果图:
黄色是头视图,红色是banner样式的item,绿色是一行多个数据的item样式,抽空把代码放在github上,恩恩.