UICollectionView 单元格垂直排列而不是网格

UICollectionView cells lining vertically instead of grid

我正在尝试以编程方式创建 UICollectionView,但我的单元格正在垂直堆叠,而不是网格形式。

我的代码是:

    let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    let screenSize: CGRect = UIScreen.main.bounds
    let screenWidth = screenSize.width

    let width = (screenWidth - 4)/3
    layout.itemSize = CGSize(width: width, height: width+20)
    layout.sectionInset = UIEdgeInsets(top:0,left:0,bottom:0,right:0)
    collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    collectionView?.dataSource = self
    collectionView?.delegate=self
    collectionView?.collectionViewLayout = layout
    collectionView?.register(NearbyCollectionViewCell.self, forCellWithReuseIdentifier: "cellId")

    self.view.addSubview(collectionView!)

您应该始终考虑 collectionView 的项目尺寸计算框架。

在您的问题中,您使用的是 UIScreen 的宽度,由于 collectionViewinset 属性,这可能会使您计算错误。

let screenSize: CGRect = UIScreen.main.bounds

let screenWidth = screenSize.width

为了正确计算尺寸,让我们定义单行中的项目数。

let maximumItemInRow = 3(你可以根据自己的需要玩这个)

现在正在实施 UICollectionViewDelegateFlowLayoutsizeForItem 方法。

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    // Getting collectionView's size
    var width = collectionView.frame.width
    var height = collectionView.frame.height
    
    // Respecting collectionView's ContentInsets properties
    width -= (collectionView.contentInset.left + collectionView.contentInset.right)
    height -= (collectionView.contentInset.top + collectionView.contentInset.bottom)
    
    if let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout {
        
        // Respecting flowLayout's sectionInset properties
        width -= (flowLayout.sectionInset.left + flowLayout.sectionInset.right)
        height -= (flowLayout.sectionInset.top + flowLayout.sectionInset.bottom)
        
        // In Vertically scrolling Flow layout
        width -= flowLayout.minimumInteritemSpacing
        height -= flowLayout.minimumLineSpacing
    }
    
    // After considering contentInset and sectionInsets 
    // we can calculate the width according to 
    // number of items in single row. 
    return CGSize(width: width / maximumItemInRow, height: height)
}

您可以按如下方式使用 UICollectionViewDelegateFlowLayout:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
    let itemWidth: CGFloat = (screenWidth - 4)/3
    let itemHeight: CGFloat = itemWidth + 20

    return CGSize(width: itemWidth, height: itemHeight)
}