我试图在UICollectionView中左对齐单元格,我使用GitHub repo尝试获取它,链接在这里: https://github.com/mischa-hildebrand/AlignedCollectionViewFlowLayout
我设置了CollectionView及其单元格,如下所示:
lazy var filterCollectionView: UICollectionView = {
let layout = AlignedCollectionViewFlowLayout(horizontalAlignment: .left, verticalAlignment: .center)
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.register(filterCell.self, forCellWithReuseIdentifier: "filterCellId")
cv.backgroundColor = .white
cv.isScrollEnabled = true
cv.dataSource = self
cv.delegate = self
cv.showsHorizontalScrollIndicator = false
return cv
}()
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return genrArray.count
}
let genArray = ["Test123", "LongTextTest", "Short", "S", "#LongLongLongLong"]
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "filterCellId", for: indexPath) as! filterCell
cell.genText.text = genArray[indexPath.row]
cell.genText.sizeToFit()
cell.frame = CGRect(x: cell.frame.origin.x, y: cell.frame.origin.y, width: cell.genText.frame.width + 25, height: 24)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let label = UILabel(frame: .zero)
label.text = genArray[indexPath.row]
label.frame = CGRect(x: 0, y: 0, width: label.intrinsicContentSize.width, height: 0)
return CGSize(width: label.frame.width + 25, height: 18)
}
这对单元格没有任何作用,所以我将这些代码行添加到ViewDidLoad()中:
let layout = AlignedCollectionViewFlowLayout(horizontalAlignment: .left, verticalAlignment: .center)
layout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
self.filterCollectionView.collectionViewLayout = layout
在CollectionView中实际进行更改的行是layout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
。但这仍然没有达到预期的效果。这会使我的细胞变形并使它们的高度远小于18(在sizeForItem
中声明的大小。加载后,collectionView看起来像这样:
但是当我滚动collectionView时,它会恢复正常,就好像左对齐布局不在那里一样。它看起来像这样:
单元格在该图像中是正确的形状,但是对齐/布局/间距是关闭的。
我做错了什么?