对齐集合视图单元格以恰好适合每行 3 个 [英] Aligning collection view cells to fit exactly 3 per row
问题描述
我正在尝试制作图像的集合视图,以便每行有 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屋!