平分屏幕宽度
的UICollectionViewCell
- 重写
layout
-
xib
定义cell
且设置约束 -
vc
中代码创建UICollectionView
, 实现代理
- 重写
layout
class NoGapLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attributes = super.layoutAttributesForElements(in: rect) else {
return nil
}
if attributes.count == 0 {
return attributes
}
let cellSpace = minimumInteritemSpacing
let rightInset = sectionInset.right
for i in 1..<attributes.count {
///1.当前attribute
let currentAttribute = attributes[I]
///2.上一个attributes
let prevLayoutAttribute = attributes[i - 1]
///3.前一个cell的最右边
let origin = prevLayoutAttribute.frame.maxX
///4.如果当前一个cell的最右边加上我们想要的间距加上当前cell的宽度依然在contentSize中,我们改变当前cell的原点位置;
///不加这个判断的后果是,UICollectionView只显示一行,原因是下面所有cell的x值都被加到第一行最后一个元素的后面了
if(origin + cellSpace + rightInset + currentAttribute.frame.size.width <= collectionViewContentSize.width) {
var frame = currentAttribute.frame
frame.origin.x = origin + cellSpace
currentAttribute.frame = frame
}
}
return attributes
}
}
- 定义
cell

-
vc
中代码
import UIKit
var rect: CGRect = .zero
let col: CGFloat = 3
let insetSpaces: CGFloat = 0
let cellSpace: CGFloat = 0
class LoadXibCellVC: UIViewController {
///collectionview
fileprivate lazy var cv: UICollectionView = {[unowned self] in
let layout: UICollectionViewFlowLayout = NoGapLayout()
layout.minimumLineSpacing = 5
layout.minimumInteritemSpacing = cellSpace
layout.sectionInset = UIEdgeInsets(top: 5, left: insetSpaces, bottom: 5, right: insetSpaces)
let v = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
v.backgroundColor = .systemRed
v.delegate = self
v.dataSource = self
v.register(UINib(nibName: "XibCell", bundle: nil), forCellWithReuseIdentifier: "XibCell")
self.view.addSubview(v)
return v
}()
var items = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
for name in 0...31 {
var str = ""
for i in 0...name {
str.append("g\(i)")
}
items.append(str)
}
self.cv.reloadData()
}
}
extension LoadXibCellVC: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XibCell", for: indexPath) as! XibCell
cell.txt = items[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let w = (collectionView.width-2*insetSpaces-(col-1)*cellSpace)/col
let h = w * 4 / 3
let itemSize = CGSize(width: (w), height: (h))
return itemSize
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
DebugLog(indexPath.item)
}
}
网友评论