将单个 UICollectionViewCell 对齐到 collectionView 的左侧

align single UICollectionViewCell to the left of the collectionView

我在 tableView 单元格中有一个 collectionView。 collectionView 有多个部分。如果一个部分只有一个单元格,则该单元格居中显示。如何将单个单元格向左对齐?

collectionView 具有以下 flowLayout:

let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .vertical
flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
flowLayout.minimumInteritemSpacing = 0
flowLayout.minimumLineSpacing = 0
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
collectionView.setCollectionViewLayout(flowLayout, animated: true)

因为sectionInsetfunc collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { }协议是一样的,可以调用这个协议来知道哪个部分只剩下一个单元格。

您可以替换:

flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

与:

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

    if collectionView.numberOfItems(inSection: section) == 1 {

         let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout

        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: collectionView.frame.width - flowLayout.itemSize.width)

    }

    return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

}

这个红色单元格是第二部分中唯一剩下的单元格,并且左对齐:

我有同样的问题。 我的解决方案是更改 collectionView 的估计大小。

自动 -> None