设置数据后调整 UICollectionView 单元格的大小 [英] Resize UICollectionView cells after their data has been set

查看:17
本文介绍了设置数据后调整 UICollectionView 单元格的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 UICollectionView 单元格包含带有多行文本的 UILabel.在标签上设置文本之前,我不知道单元格的高度.

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?

推荐答案

我认为您正在寻找可以在您的 .collectionViewLayout 属性上调用的 invalidateLayout 方法UICollectionView.此方法会重新生成您的布局,在您的情况下,这意味着还调用 -collectionView: layout: sizeForItemAtIndexPath:,这是反映所需项目大小的正确位置.Jirune 指出了如何计算它们的正确方向.

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.

invalidateLayout 的使用示例可见 这里.另请参阅有关该方法的 UICollectionViewLayout 文档:

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.

讨论:

您可以随时调用此方法来更新布局信息.此方法使集合视图本身的布局无效并立即返回.因此,您可以从同一个代码块中多次调用此方法,而不会触发多次布局更新.实际的布局更新发生在下一个视图布局更新周期.

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.

对于包含自动布局约束的storyboard collection view,你需要重写UIViewControllerviewDidLayoutSubviews方法,并在此调用invalidateLayout collection view layout方法.

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆