简体   繁体   English

如何居中对齐CollectionView单元格?

[英]How to center align CollectionView Cell?

Hi have a collectionview. 嗨,有一个collectionview。 Each cell's width is screenwidth/3. 每个单元的宽度为screenwidth / 3。 Means 3 cells in a row. 表示连续3个单元格。 Now. 现在。 If have 10 or 11 cells then there will be 4 rows. 如果有10或11个像元,则将有4行。 and there are 1 or 2 cells in last row. 最后一行有1或2个单元格。 The problem is ,I want to align these cell to center without changing its size . 问题是,我想在不更改其大小的情况下将这些单元对齐到中心。 now cells are left align. 现在,单元格左对齐。

Note: I want to achieve this with in a section(Because collection-view already have multiple sections). 注意:我想在一个部分中实现此目的(因为collection-view已经有多个部分)。 Image attached what i want to achieve . 图片附上我想实现的目标。 在此处输入图片说明

You can solve this using multiple sections. 您可以使用多个部分来解决此问题。 Number of section should be 条数应为

numberOfSection = totalItemCount/3 > Int(totalItemCount/3) ? Int(totalItemCount/3) + 1 : Int(totalItemCount/3)

dont use ceiling. 不要使用天花板。 Then number of items in section should be 然后该部分中的项目数应为

numberOfItemInSection = totalItemCount-section*3 < 3 ? totalItemCount-section*3 : 3

Then implement the UICollectionViewDelegateFlowLayout delegate. 然后实现UICollectionViewDelegateFlowLayout委托。 Where in collectionView(_ collectionView:, layout:, insetForSectionAt:) set, collectionView(_ collectionView:, layout:, insetForSectionAt:)设置的位置,

let minimumInterItemSpacing: CGFloat = 8.0
// minimumInterItemSpacing should be same in the delegate function
let itemCountInSection = collectionView.numberOfItems(inSection: section)
let edgeSpace = (collectionView.bounds.width - ((itemCountInSection*self.itemWidth) + (minimumInterItemSpacing*(itemCountInSection-1)))) / 2
return UIEdgeInsets(top: self.topSpace, left: edgeSpace, bottom: self.bottomSpace, right: edgeSpace)

set other delegate methods as it suits you. 设置其他适合您的委托方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM