集合视图间距很宽

Collection view spacing is very wide

我的 collectionView 之间的间距很宽,我该如何解决?

问题图片。

代码:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return songs.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "song-cell", for: indexPath) as? SongsCollectionViewCell {

        cell.albumArtwork.image = songs[indexPath.row].images
        cell.songName.text = songs[indexPath.row].name
        cell.songArtist.text = songs[indexPath.row].composer

        return cell
    }

    return UICollectionViewCell()
}

遵循 UICollectionViewDelegateFlowLayout 协议并实现这些方法。 您只需根据需要为集合单元格操纵 return 值。

 // This method will create collectionView cell size. Delegate method of UICollectionViewDelegateFlowLayout.
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 200.0, height: 200.0)
    }

    // This method will create horizontal padding between two cells. Delegate method of UICollectionViewDelegateFlowLayout.
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 5.0
    }

    // This method will create vertical padding between upper cell and lower cell. Delegate method of UICollectionViewDelegateFlowLayout.
    func collectionView(_ collectionView: UICollectionView, layout
        collectionViewLayout: UICollectionViewLayout,
                        minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10.0
    }

试试这个。

let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    flowLayout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    flowLayout.itemSize = CGSize(width: 150.0, height: 150.0)
    flowLayout.minimumInteritemSpacing = 0 // for vertical spacing
    flowLayout.minimumLineSpacing = 0 // for horizontal spacing
    your_collectionView.collectionViewLayout = flowLayout