设置数据后,调整UICollectionView单元格的大小 [英] Resize UICollectionView cells after their data has been set
问题描述
我的UICollectionView单元格包含带有多行文本的UILabel.在标签上设置文本之前,我不知道单元格的高度.
-(CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout*)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
这是我用来确定单元格大小的最初方法.但是,这被称为在情节提要之外创建单元之前.
有没有一种方法可以对收集的单元格进行布局并设置其大小,并且知道它们的实际大小?
我认为您正在寻找可以在UICollectionView的.collectionViewLayout
属性上调用的invalidateLayout
方法.此方法将重新生成布局,在您的情况下,这意味着还调用-collectionView: layout: sizeForItemAtIndexPath:
,这是反映所需项目大小的正确位置. Jirune为如何计算它们指明了正确的方向.
invalidateLayout
用法示例可在此处一个>.另请参阅该方法的UICollectionViewLayout文档:
使当前布局无效并触发布局更新.
讨论:
您可以随时调用此方法来更新布局信息.此方法使集合视图本身的布局无效,并立即返回.因此,您可以从同一代码块中多次调用此方法,而无需触发多个布局更新.实际的布局更新发生在下一个视图布局更新周期中.
对于包含自动布局约束的情节提要板集合视图,您需要覆盖UIViewController
的viewDidLayoutSubviews
方法并在此方法中调用invalidateLayout
集合视图布局.
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
[yourCollectionView.collectionViewLayout invalidateLayout];
}
My UICollectionView cells contain UILabels with multiline text. I don't know the height of the cells until the text has been set on the label.
-(CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout*)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
This was the initial method I looked at to size the cells. However, this is called BEFORE the cells are created out of the storyboard.
Is there a way to layout the collection and size the cells AFTER they have been rendered, and I know the actual size of the cell?
I think your are looking for the invalidateLayout
method you can call on the .collectionViewLayout
property of your UICollectionView. This method regenerates your layout, which in your case means also calling -collectionView: layout: sizeForItemAtIndexPath:
, which is the right place to reflect your desired item size. Jirune points the right direction on how to calculate them.
An example for the usage of invalidateLayout
can be found here. Also consult the UICollectionViewLayout documentation on that method:
Invalidates the current layout and triggers a layout update.
Discussion:
You can call this method at any time to update the layout information. This method invalidates the layout of the collection view itself and returns right away. Thus, you can call this method multiple times from the same block of code without triggering multiple layout updates. The actual layout update occurs during the next view layout update cycle.
Edit:
For storyboard collection view which contains auto layout constraints, you need to override viewDidLayoutSubviews
method of UIViewController
and call invalidateLayout
collection view layout in this method.
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
[yourCollectionView.collectionViewLayout invalidateLayout];
}
这篇关于设置数据后,调整UICollectionView单元格的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!