首页 > 解决方案 > 如何减少 UICollection 视图中的垂直间距

问题描述

我在UICollectionView下面使用的是我的代码,如何删除垂直间距?我尝试设置UICollectionViewFlowLayout但没有工作。

class ViewController: UIViewController {
    
    @IBOutlet weak var cv: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        cv.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        let xx : CGFloat = (UIScreen.main.bounds.width / 8)
        let yy : CGFloat = 6.0
        layout.itemSize = CGSize(width: xx, height: yy)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 1
        cv!.collectionViewLayout = layout
    }
}

extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 70
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        if (indexPath.row/2 == 0) {
            cell.backgroundColor = UIColor.blue.withAlphaComponent(12)
        }
        else if (indexPath.row/4 == 0) {
            cell.backgroundColor = UIColor.blue.withAlphaComponent(0.5)
        }
        else{
            cell.backgroundColor = UIColor.blue.withAlphaComponent(0.1)
        }
        return cell
    }
}

在此处输入图像描述

标签: iosswiftuicollectionviewuicollectionviewcell

解决方案


您的情况下的间距是由每个项目的尺寸 - 宽度,主要是 - 引起的。

所以你有这个代码来计算你的单件宽度:

let xx : CGFloat = (UIScreen.main.bounds.width / 8)

但是由于您有部分插图,因此您的计算必须更改,或者您必须删除插图,因此:

let xx : CGFloat = (UIScreen.main.bounds.width - 10 / 8)
// 10 = 5 left + 5 right is taken for section insets

或者,删除您的部分插图:

// layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)

如果你想给出前导/尾随边距,请改用集合约束,即用常量(比如 5)约束它的超级视图collectionViewleadingAnchor/ trailingAnchor,那么你不必进行计算,因为你可以使用sizeForItem委托方法和以这种方式返回计算:

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.bounds.width / 8, height: 5.0)
 }

推荐阅读