gpt4 book ai didi

ios - 如何水平居中自动调整 UICollectionView 单元格?

转载 作者:搜寻专家 更新时间:2023-10-31 19:27:36 27 4
gpt4 key购买 nike

我有一个 collectionView,方向设置为水平,每个单元格只包含一个 UIlabel,它使用自动布局来确定单元格的宽度。

例如,有三个单元格,这是默认行为。

|[x] [xxx] [xxxxxxxxx] |

但如果所有单元格的总宽度不超过屏幕宽度,则要求将这三个单元格居中对齐。

第一个单元格的左插图应该是

leftInset = (屏幕宽度 - (第一个单元格宽度 + 第二个单元格宽度 + 第三个单元格宽度 + 三个单元格之间的总间距)/) 2

结果是

| [x] [xxx] [xxxxxxxxx] |

我从 How to center horizontally UICollectionView Cells? 中找到了固定宽度单元格的一个很好的答案,但不适用于自尺寸的。

如有帮助,将不胜感激。

最佳答案

真的很烦人,Apple 没有为这些东西提供现成的布局...

最后我想出了以下流程布局:

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
}
}

这基本上包括以下步骤:

  1. 计算contentWidth
  2. 计算 contentWidthcollectionView 宽度之间的(左+右)margin
  3. 必要时应用边距*,这会导致输入内容

* 负边距意味着内容大于 collectionView,因此属性应保持不变 => 可滚动且左对齐,正如人们所期望的那样。

关于ios - 如何水平居中自动调整 UICollectionView 单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47999130/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com