集合视图间距非常宽

时间:2019-02-25 07:40:12

标签: swift xcode uicollectionview spacing

collectionViews之间的间距非常宽,如何解决此问题?

问题图片。

problem

代码:

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()
}

2 个答案:

答案 0 :(得分:1)

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

 // 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
    }

答案 1 :(得分: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