Collectionview和分页

时间:2017-08-08 15:12:41

标签: ios swift

我想使用收集视图来显示用户的Instagram照片,如Tinder。我放置了一个collectionview和启用分页。但我不知道如何为每页显示6张照片。我怎样才能做到这一点?

这就是我想要的:

第一页:

enter image description here

第二页:

enter image description here

我使用了所有间距设置为零,因为从不同屏幕尺寸的故事板问题设置间距。

我的收藏视图的设置和结果:

enter image description here

结果:

enter image description here

所以我想每页显示6张照片。如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

要显示所需的特定细胞数,您必须计算细胞的大小。像这样:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let numberOfRows = 2
    let numberOfColumns = 3

    let height = collectionView.frame.size.height / numberOfRows
    let width = collectionView.frame.size.width / numberOfColumns

    let cellSize = CGSize(width: width, height: height)

    return cellSize
}

由于您的布局配置是静态的,因此您只需计算一次以使其更快:

class MyVC: UIViewController {

    private let cellSize: CGSize = CGSize(width: collectionView.frame.width/numberOfColumns, height: collectionView.frame.height/numberOfRows) // or create a computed property

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return cellSize
    }
}

这段代码未经测试,也许你必须添加一些填充,但你明白了。另一种选择是实现自己的UICollectionViewLayout子类

相关问题