我有一个 Storyboard ,由一个 UICollectionView
和多个单元格组成,每个单元格的高度各不相同。第一个单元格采用 UICollectionViewDelegateFlowLayout
的高度:
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
.. 但我希望第二个单元格更短。
我在单元格内的“主”UIStackView
中放置了两个 UIStackViews
,每个内部 UIStackViews
都有一个或多个标签,例如这个:
cell
--> stackView (master)
--> stackView (1)
--> label
--> stackView (2)
--> label
--> label (etc)
.. 希望 UIStackView
可以使单元格高度动态,但事实并非如此。它像以前一样从 UICollectionViewDelegateFlowLayout
获取高度。
我应该怎么做?
最佳答案
您需要计算 CollectionViewCell
的内容大小并将其返回给 sizeForItemAt
函数。
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
// Create an instance of the `FooCollectionViewCell`, either from nib file or from code.
// Here we assume `FooCollectionViewCell` is created from a FooCollectionViewCell.xib
let cell: FooCollectionViewCell = UINib(nibName: "FooCollectionViewCell", bundle: nil)
.instantiate(withOwner: nil, options: nil)
.first as! FooCollectionViewCell
// Configure the data for your `FooCollectionViewCell`
cell.stackView.addArrangedSubview(/*view1*/)
cell.stackView.addArrangedSubview(/*view2*/)
// Layout the collection view cell
cell.setNeedsLayout()
cell.layoutSubviews()
// Calculate the height of the collection view based on the content
let size = cell.contentView.systemLayoutSizeFitting(
CGSize(width: collectionView.bounds.width, height: 0),
withHorizontalFittingPriority: UILayoutPriorityRequired,
verticalFittingPriority: UILayoutPriorityFittingSizeLevel)
return size
}
这样,您将拥有动态单元格高度 UICollectionView
。
补充说明:
对于 Collection View 单元格的配置,您可以在
FooCollectionViewCell
上创建一个辅助函数func configure(someData: SomeData)
以便共享代码在cellForItemAt
函数和sizeForItemAt
函数之间。// Configure the data for your `FooCollectionViewCell` cell.stackView.addArrangedSubview(/*view1*/) cell.stackView.addArrangedSubview(/*view2*/)
对于这两行代码,似乎只有当
UICollectionViewCell
包含垂直UIStackView
作为 subview 时才需要(可能是 Apple 的错误)。// Layout the collection view cell cell.setNeedsLayout() cell.layoutSubviews()
关于ios - UICollectionView:使用 UIStackView 的动态单元格高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33965415/