如何居中对齐我的 collectionView 单元格?
Posted
技术标签:
【中文标题】如何居中对齐我的 collectionView 单元格?【英文标题】:How do I center align my collectionView cells? 【发布时间】:2017-12-13 19:21:53 【问题描述】:我试过这个解决方案here,但它似乎只适用于垂直布局。我正在尝试使其适用于水平布局。就我而言,我总是希望顶部有 3 个单元格,底部有 2 个单元格,并且中心对齐。
例如:
【问题讨论】:
对不起@MilanNosáľ 我应该说它并不总是 5 个单元格,它可以是任意数量的单元格。我的问题是如何管理布局,以便它始终以我想要的格式显示我的单元格 这个问题有什么更新吗? 【参考方案1】:我认为这应该对您有所帮助(我在委托方法中定义了插图,因为 collectionview 否则只会将我的第一个部分居中而其他部分保持不变):
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
// handling layout
// which needs to be centered vertically and horizontally
// also:
// maximum number of items = 6
// maximum number of rows = 2
// maximum number of items in row = 3
let numberOfItems: CGFloat
let numberOfRows: CGFloat
if collectionView.numberOfItems(inSection: section) > Constants.maxNumberOfItemsInRow
numberOfItems = CGFloat(Constants.maxNumberOfItemsInRow)
numberOfRows = CGFloat(Constants.maxNumberOfRows)
else
numberOfItems = CGFloat(collectionView.numberOfItems(inSection: section))
numberOfRows = CGFloat(Constants.minNumberOfRows)
let totalCellWidth = Constants.itemSize.width * numberOfItems
let totalSpacingWidth = Constants.minimumInteritemSpacing * numberOfItems
var leftInset = (collectionView.layer.frame.size.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2
let totalCellHeight = Constants.itemSize.height * numberOfRows
let maximumSectionHeight = (Constants.itemSize.height * CGFloat(Constants.maxNumberOfRows)) + (CGFloat(Constants.maxNumberOfRows + 1) * Constants.minimumLineSpacing)
if leftInset < 0.0 leftInset = 0.0
let topInset = (maximumSectionHeight - totalCellHeight) / 2
let rightInset = leftInset
return UIEdgeInsets(top: topInset, left: leftInset, bottom: topInset, right: rightInset)
另外,布局是由类定义的:
class CollectionViewFlowLayout: UICollectionViewFlowLayout
// MARK: - Constants
private struct Constants
static let minimumInteritemSpacing: CGFloat = 12.5
static let minimumLineSpacing: CGFloat = 16.5
static let itemSize = CGSize(width: 64.0, height: 90.0)
override func prepare()
guard let collectionView = collectionView else return
/// Defining flow layout for collectionview presentation
itemSize = Constants.itemSize
headerReferenceSize = CGSize(width: collectionView.dc_width, height: 1)
scrollDirection = .vertical
minimumInteritemSpacing = Constants.minimumInteritemSpacing
minimumLineSpacing = Constants.minimumLineSpacing
super.prepare()
【讨论】:
以上是关于如何居中对齐我的 collectionView 单元格?的主要内容,如果未能解决你的问题,请参考以下文章