Я пытаюсь выровнять ячейки по левому краю в UICollectionView, и я использовал репозиторий GitHub, чтобы попытаться получить это, ссылка здесь: 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 выглядит так:
![First Load of CollectionView](https://i.stack.imgur.com/GczRl.png)
Но когда я прокручиваю collectionView, он возвращается к нормальному состоянию, как если бы левого макета выравнивания даже не было. Затем он выглядит так:
![CollectionView after scrolling through](https://i.stack.imgur.com/fQZuT.png)
Ячейки имеют правильную форму на этом изображении, но выравнивание / расположение / интервал отключены.
Что я делаю не так?