如何在swift 4中心显示CollectionViewCell

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

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

enter image description here

如何在中心对齐中显示collectionViewCell?我想显示如下图像

enter image description here

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

ios uicollectionview swift4 uicollectionviewcell uicollectionviewlayout
1个回答
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

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