将单个UICollectionViewCell对齐到collectionView的左侧

问题描述 投票:4回答:1

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

collectionView inside tableView cell

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)
swift uitableview uicollectionview uicollectionviewcell uicollectionviewlayout
1个回答
0
投票

由于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 {
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: collectionView.frame.width * 4 / 5) // calculate your .sectionInset.right          
    }

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

}
© www.soinside.com 2019 - 2024. All rights reserved.