对齐集合视图单元格以恰好适合每行3个 [英] Aligning collection view cells to fit exactly 3 per row

查看:138
本文介绍了对齐集合视图单元格以恰好适合每行3个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作图像的集合视图,因此每行有3个,两者之间没有间距。

I am trying to make a collection view of images, so that there are 3 per row, with no spacing in between.

我的集合视图数据源是:

My collection view data sources are:

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

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

这就是它的设置方式在我的故事板中(imageView宽度为125,是375屏幕宽度的三分之一):

and this is how it's set up in my storyboard (imageView width is 125, a third of the 375 screen width):

然而,当我运行应用程序并添加一些照片时,它看起来像这样:

However when I run the app and add some photos, it looks like this:

如何解决此问题,以便每行看到3张图片?感谢您的帮助!

How can I fix this so that I see 3 images per row? Thanks for any help!

推荐答案

您必须实施


UICollectionViewDelegateFlowLayout

UICollectionViewDelegateFlowLayout

的间距内容。

像这样设置collectionViewCells的大小:

Set the size of the collectionViewCells like this:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let yourWidth = collectionView.bounds.width/3.0
    let yourHeight = yourWidth

    return CGSize(width: yourWidth, height: yourHeight)
}

您还可以添加这些函数以使collectionViewCells的间距正确:

You can also add these functions to get your spacing of the collectionViewCells correct:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets.zero
}

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

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

这篇关于对齐集合视图单元格以恰好适合每行3个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆