UICollectionView:删除单元格之间的空间(每行7个项目)

时间:2019-02-27 22:04:49

标签: ios uicollectionview

我有一个UICollectionView每行有7个项目(或者实际上,每个项目的宽度是collectionView.bounds.width除以7)。

这是一个代码示例:

final class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    let randomColors: [UIColor] = [.red, .blue, .green, .yellow, .orange, .purple, .cyan, .gray, .darkGray, .lightGray, .magenta]

    var colors: [UIColor] {
        var result: [UIColor] = []
        for _ in 0..<200 {
            result.append(randomColors[Int(arc4random_uniform(UInt32(randomColors.count - 1)))])
        }
        return result
    }

    @IBOutlet weak var collectionView: UICollectionView!

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

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return .leastNormalMagnitude
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return .leastNormalMagnitude
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: .leastNormalMagnitude, left: .leastNormalMagnitude, bottom: .leastNormalMagnitude, right: .leastNormalMagnitude)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return colors.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ColorCollectionViewCell", for: indexPath) as! ColorCollectionViewCell
        cell.color = colors[indexPath.row]
        return cell
    }

}


final class ColorCollectionViewCell: UICollectionViewCell {

    var color: UIColor? {
        didSet {
            self.backgroundColor = color
        }
    }

}

和情节提要:

enter image description here

由于将collectionView的宽度除以7通常会产生浮动结果,因此会导致在某些单元格之间出现空格:

enter image description here

我在这里可以做什么?

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您必须以某种方式分配其他像素。不用担心所有单元格的宽度都不完全相同,不会出现1px的差异:

let numColumns = 7
let availableWidth = collectionView.bounds.size.width
let minWidth = floor(availableWidth / CGFloat(numColumns))
let remainder = availableWidth - minWidth * CGFloat(numColumns)

现在如何处理其余部分?让我们从左侧向单元格添加像素:

let columnIndex = indexPath.row % numColumns
let cellWidth = CGFloat(columnIndex) < remainder ? minWidth + 1 : minWidth
return CGSize(width: cellWidth, height: 45)

这只是基本想法。