Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/121.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在swift 4的中心显示CollectionViewCell_Ios_Uicollectionview_Swift4_Uicollectionviewcell_Uicollectionviewlayout - Fatal编程技术网

Ios 如何在swift 4的中心显示CollectionViewCell

Ios 如何在swift 4的中心显示CollectionViewCell,ios,uicollectionview,swift4,uicollectionviewcell,uicollectionviewlayout,Ios,Uicollectionview,Swift4,Uicollectionviewcell,Uicollectionviewlayout,Collectionview单元格在一行中有两个项目,但Collectionview单元格在我的设计中不居中 如何以中心对齐方式显示collectionViewCell?我想显示如下图所示 我尝试了很多次,无法显示CollectionView的中心。请帮帮我 工作代码Swift 4 | Swift 5 您需要像这样使用UICollectionViewDelegateFlowLayout方法 class CardListViewController:UICollectionViewDelega

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

如何以中心对齐方式显示collectionViewCell?我想显示如下图所示


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

工作代码Swift 4 | Swift 5

您需要像这样使用UICollectionViewDelegateFlowLayout方法

class CardListViewController:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    // UICollectionViewDelegateFlowLayout Delegate method

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        let leftAndRightPaddings: CGFloat = 45.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
    
    }
}
输出:


尝试减少单元格间隔在我的测试中,当运行委托方法时,
SizeForestMat
collectionView.frame.width给出的宽度不是实际的运行时宽度,但仍然是在设计时从Interface Builder获取的宽度。因此,只有在IB中使用的同一台设备上进行测试时,它才会起作用。当您在不同的设备上以不同的屏幕大小运行它时,事情就会停止工作。你注意到了吗?