[英]How to center horizontally self-sizing UICollectionView Cells?
I have a collectionView and the direction is set to Horizontal and every cell just contain a UIlabel and it's using autolayout to determine the width of the cell. 我有一个collectionView,方向设置为Horizontal,每个单元格只包含一个UIlabel,它使用autolayout来确定单元格的宽度。
for example, there are three cells and it's default behaviour. 例如,有三个单元格,它是默认行为。
|[x] [xxx] [xxxxxxxxx] |
but the requirement is to center align these three cells if the total width of all cells doesn't exceed the width of the screen. 但是如果所有单元的总宽度不超过屏幕的宽度,则要求对这三个单元进行居中对齐。
the left inset for the first cell should be 第一个单元格的左边插图应该是
leftInset = (screen width - (first cell width + second cell width + third cell width + total spaces between the three cells) /) 2
the result would be 结果将是
| [x] [xxx] [xxxxxxxxx] |
I have found a great answer for the cells with fixed width from How to center horizontally UICollectionView Cells? 我找到了一个很好的答案,固定宽度的单元格从如何水平UICollectionView单元中心? , but doesn't work on self-size one.
,但不适用于自我尺寸的。
would be much appreciated if you would help. 如果你能提供帮助,我将不胜感激。
Really annoying, that Apple doesn't provide ready-to-use layouts for such things... 真的很烦人,Apple没有为这类东西提供现成的布局......
In the end I came up with following flow layout: 最后我想出了以下流程布局:
class HorizontallyCenteredCollectionViewFlowLayout: UICollectionViewFlowLayout {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.scrollDirection = .horizontal
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attributes = super.layoutAttributesForElements(in: rect) else { return nil }
guard let collectionView = self.collectionView,
let rightmostEdge = attributes.map({ $0.frame.maxX }).max() else { return attributes }
let contentWidth = rightmostEdge + self.sectionInset.right
let margin = (collectionView.bounds.width - contentWidth) / 2
if margin > 0 {
let newAttributes: [UICollectionViewLayoutAttributes]? = attributes
.compactMap {
let newAttribute = $0.copy() as? UICollectionViewLayoutAttributes
newAttribute?.frame.origin.x += margin
return newAttribute
}
return newAttributes
}
return attributes
}
}
This basically consists of the following steps: 这基本上包括以下步骤:
contentWidth
contentWidth
margin
between the contentWidth
and the collectionView
s width contentWidth
和collectionView
的宽度之间的(左+右) margin
* Negative margin means the content is bigger than the collectionView
and the attributes should therefore stay unchanged => scrollable and left aligned as one would expect. *负边距意味着内容大于
collectionView
,因此属性应保持不变=>可滚动并按照预期左对齐。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.