gpt4 book ai didi

uicollectionview - 使用 invalidateLayout 加载数据后调整 UICollectionViewCell 的大小

转载 作者:行者123 更新时间:2023-12-04 08:49:04 26 4
gpt4 key购买 nike

这个问题已被问过几次,但没有一个答案足够详细,让我无法理解为什么/如何工作。作为引用,其他 SO 问题是:

How to update size of cells in UICollectionView after cell data is set?

Resize UICollectionView cells after their data has been set

Where to determine the height of a dynamically sized UICollectionViewCell?

我正在使用 MVC,但为了简单起见,可以说我有一个 ViewController,它在 ViewWillAppear 中调用 Web 服务来加载一些数据。加载数据后,它会调用

[self.collectionView reloadData]

self.collectionView 包含 1 个 UICollectionViewCell(我们称之为 DetailsCollectionViewCell)。

创建 self.collectionView 时,它首先调用 sizeForItemAtIndexPath,然后调用 cellForItemAtIndexPath。这给我带来了一个问题,因为只有在 cellForItemAtIndexPath 期间,我通过以下方式将 Web 服务的结果设置为 DetailsCollectionViewCell:
    cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"detailsCell" forIndexPath:indexPath];
((DetailsCollectionViewCell*)cell).details = result;

DetailsCollectionViewCell 有一个属性详细信息的 setter ,它做了一些工作,我首先需要知道正确的单元格大小应该是多少。

根据上面的链接问题,似乎在 cellForItemAtIndexPath 之后触发 sizeForItemAtIndexPath 的唯一方法是调用
[self.collectionView.collectionViewLayout invalidateLayout];

但这是其他问题对我不起作用的地方,因为虽然它调用 sizeForItemAtIndexPath 并允许我从 DetailsCollectionViewCell 获取足够的信息来设置正确的高度,但它不会更新 UI,直到用户滚动 UICollectionView 而我的猜测是它与文档中的这一行有关

The actual layout update occurs during the next view layout update cycle.



但是,我很难解决如何解决这个问题。感觉就像我需要在 DetailsCollectionViewCell 上创建一个静态方法,我可以在第一次 sizeForItemAtIndexPath 传递期间将 Web 服务结果传递给它,然后只缓存该结果。但我希望有一个简单的解决方案可以让 UI 自动更新。

谢谢,

p.s. - 第一个 SO 问题,希望我正确遵守所有规则。

最佳答案

实际上,根据我的发现,调用 invalidateLayout 将导致在下一个单元格出列时为所有单元格调用 sizeForItemAtIndexPath (这是针对 iOS < 8.0,因为 8.0 它将在下一次 View 布局更新中重新计算布局)。

所以我想出的解决方案是子类化 UICollectionView,并用类似这样的东西覆盖 layoutSubviews:

- (void)layoutSubviews
{
if ( self.shouldInvalidateCollectionViewLayout ) {
[self.collectionViewLayout invalidateLayout];
self.shouldInvalidateCollectionViewLayout = NO;
} else {
[super layoutSubviews];
}
}

然后调用 setNeedsLayoutcellForItemAtIndexPath和设置 shouldInvalidateCollectionViewLayout是的。这在 iOS >= 7.0 中对我有用。我也以这种方式实现了估计的项目大小。谢谢。

关于uicollectionview - 使用 invalidateLayout 加载数据后调整 UICollectionViewCell 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23727639/

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