2

我正在尝试以编程方式创建 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!)
4

2 回答 2

3

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

在您的问题中,您使用UIScreen' 的宽度可能会因为collectionView' 的inset属性而导致错误的计算。

让 screenSize: CGRect = UIScreen.main.bounds

让 screenWidth = screenSize.width

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

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

现在实现UICollectionViewDelegateFlowLayout'sizeForItem方法。

 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)
}
于 2018-08-05T15:08:09.240 回答
0

您可以使用 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)
}
于 2018-08-05T15:08:55.480 回答