如何在Swift 4的中心显示CollectionViewCell

时间:2019-02-13 14:04:50

标签: ios uicollectionview swift4 uicollectionviewcell uicollectionviewlayout

Collectionview单元格在一行中有两个项目,但是Collectionview单元格不在我的设计中心。

enter image description here

如何以居中对齐显示collectionViewCell?我想显示如下图

enter image description here

我尝试了很多次,无法显示CollectionView的中心。请帮帮我!

2 个答案:

答案 0 :(得分:1)

工作代码 Swift 4

您需要使用 UICollectionViewDelegateFlowLayout 这样的方法

class CardListViewController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{

    // UICollectionViewDelegateFlowLayout Delegate method

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        let leftAndRightPaddings: CGFloat = 30.0
        let numberOfItemsPerRow: CGFloat = 2.0

        let width = (collectionView.frame.width-leftAndRightPaddings)/numberOfItemsPerRow
        return CGSize(width: width, height: width) // You can change width and height here as pr your requirement

    }
}

从“情节提要”集的节插入像这样。

enter image description here

输出:

enter image description here

答案 1 :(得分:-1)

进行以下更改:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
    let numberOfItemsPerRow: CGFloat = 2.0
    let minimumCellSpacing: CGFloat = 10.0
    let totalSpacing = (numberOfItemsPerRow + 1)*minimumCellSpacing //left + right + in-between padding
    let width = (collectionView.frame.width - totalSpacing)/numberOfItemsPerRow
    return CGSize(width: width, height: width) 

}

一旦完成。

稍微延迟在主线程中重新加载您的集合视图:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.10) {
   self.myCollectionView.reloadData()
}