如何水平居中UICollectionView细胞? [英] How to center horizontally UICollectionView Cells?
问题描述
我做了一些研究,但是我找不到任何关于如何在UICollectionView中水平居中单元格的代码示例。
I have done some research, but I couldn't find any code example on how to center cells in a UICollectionView horizontally.
而不是第一个单元格像这个 X00 ,我希望它像 0X0 。有没有办法实现这个目标?
instead of the first cell being like this X00, I want it to be like this 0X0. is there any way to accomplish this?
编辑:
可视化我想要的东西:
当CollectionView中只有一个元素时,我需要它看起来像版本B.当我有多个元素时,它应该像版本A但有更多元素。
I need it to look like version B when there is only one element in the CollectionView. When I got more than one element, then it should be like version A but with more elements.
目前,当我只有1个元素时它看起来像版本A,我想知道如何让它看起来像B。
At the moment it looks like Version A when I have only 1 element, and I wonder how I can make it look like B.
感谢您的帮助!
推荐答案
使用库不是一个好主意,如果你的目的只是这个,即中心对齐。
Its not a good idea to use a library, if your purpose is only this i.e to centre align.
你最好能做这个简单的计算在你的collectionViewLayout函数中。
Better you can do this simple calculation in your collectionViewLayout function.
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
let totalCellWidth = CellWidth * CellCount
let totalSpacingWidth = CellSpacing * (CellCount - 1)
let leftInset = (collectionViewWidth - CGFloat(totalCellWidth + totalSpacingWidth)) / 2
let rightInset = leftInset
return UIEdgeInsetsMake(0, leftInset, 0, rightInset)
}
这篇关于如何水平居中UICollectionView细胞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!