问题描述
我正在使用UICollectionViewFlowLayout。我的单元格包含高度不同的UILabel(行数)。
I'm using UICollectionViewFlowLayout. My cells contain UILabels that differ in height (number of lines).
似乎获取单元格高度的最佳方法是在<$ c $的子类中c> UICollectionViewCell ,因为这是我设置布局并可以访问我的视图的内在大小的地方,但是:
It seems that the best way to get the cell height would be in the subclass of UICollectionViewCell
, because that is where I set the layout and have access to intrinsic size of my views, BUT:
collectionView:layout:sizeForItemAtIndexPath:
在 collectionView:cellForItemAtIndexPath:
委托方法之前被调用,这意味着我需要知道之前的单元格高度我有单元格的实际布局。
collectionView: layout: sizeForItemAtIndexPath:
is called before the collectionView: cellForItemAtIndexPath:
delegate method, which means that I need to know the cell height before I have the actual layout of the cell.
到目前为止,我提出的所有内容都显得过于复杂,例如以固定单元格高度开始,引用单元格中标签后的实际高度以正确的高度再次加载和重新加载数据。有没有更好的方法呢?
Everything I came up with so far seems too complicated, like starting with fixed cell height, referencing actual height after labels in the cell load and reloading the data again with correct height. Is there a better way to do this?
推荐答案
不幸的是,没有。
对于UICollectionView中动态调整大小的项目,您需要在创建单元格之前知道或计算单元格的大小。执行此操作的传统方法是将数据存储在数组中的每一行,然后在 collectionView:layout:sizeForItemAtIndexPath:
中计算该数据的大小。
For dynamically sized items in UICollectionView you need to know or compute the size of the cell before it is created. The traditional way to do this is to store the data for each row in an array and then compute the size of that data in collectionView:layout:sizeForItemAtIndexPath:
.
例如,如果你有一个要显示的文本数组,你可以在数组中存储 NSString
对象,测量该字符串在 collectionView:layout:sizeForItemAtIndexPath:
并返回大小。 UICollectionView
然后获取该大小并调用 initWithFrame:
或 setFrame:
配置单元格视图时。
For example, if you had an array of text to be displayed you could store the NSString
objects in an array, measure that string in collectionView:layout:sizeForItemAtIndexPath:
and return the size. UICollectionView
then takes that size and calls initWithFrame:
or setFrame:
when configuring your cell's view.
如果这些尺寸不经常更改,那么缓存这些尺寸也不错。
It's also not a bad idea to cache these sizes if they don't change often.
这篇关于在哪里确定动态大小的UICollectionViewCell的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!