ios - 在 UicollectionViewCell 中更新 CollectionView 的大小

标签 ios objective-c uicollectionview uicollectionviewcell

我发现有些问题需要解决。

我正在制作一个带有 uicollectionview 的应用程序,其中单元格可以在其中包含另一个 uicollectionview,等等。 单元格的大小是该单元格内 uicollectionview 的完整内容大小。

假设我在应用程序中有这个结构:

MainCollection
    --Cell
        ...
    --Cell_6
      --ColectionviewA
        --Cell
          ...
        --Cell_66
          -- CollectionViewB
              --Cell_667

例如,Cell_667 的大小是从网络下载的异步图像大小的总动态 Accordion 。单元格下载为图像后,需要更新其大小。

当我发现我的问题时,我如何调用单元格的 “collectionview father” 更新它的大小,然后建议是“父亲”到更新大小,直到到达 MainCollection。

类似于:

Cell_667(updateSizeCell) -> CollectionViewB(updateFrameSize) -> Cell_66(updateSizeCell) -> CollectionviewA (updateFrameSize) -> Cell_6(updateSizeCell)-> MainCollection(updatecontentSize)

目标是维护单个滚动条。 我的简单解决方案是建议 MainCollection 重新加载所有单元格,但我想避免这种情况。知道如何使这种方式更高效、更干净吗?

任何提示将不胜感激。 提前致谢。

最佳答案

您基本上要做的是找出 Collection View 的 contentSize 何时发生变化。有几种方法可以实现这一点。

最直接的方法可能是使用键值观察。

初始化每个 Collection View 后,像这样将观察者添加到它们中:

[myCollectionView addObserver:self forKeyPath:NSStringFromSelector(@selector(contentSize)) options:0 context:nil];

然后,实现实际的观察方法:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqualToString:NSStringFromSelector(@selector(contentSize))])
    {
        UICollectionView *updatedCollectionView = (UICollectionView *)object;
        // update whatever you need to update here.
    }
}

最后一点就是要记住在释放观察者时移除观察者(以防 View 比观察者活得更久)

[myCollectionView removeObserver:self forKeyPath:NSStringFromSelector(@selector(contentSize))];

有关更多信息,请查看 the documentationMattt Thompson's great post about it .

关于ios - 在 UicollectionViewCell 中更新 CollectionView 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24665189/

相关文章:

ios - iPhone 设备中的位置问题

ios - 检测 NSUserDefaults 的变化

swift - UICollectionView 数据源方法不会被调用

ios - 与第三方静态框架作为单一框架构建Swift动态框架

ios - 需要 xcdatamodel 吗?

ios - 找不到框架错误 Xcode 8

ios - UITableView 不使用 UISearchBar 滚动

iphone - 在没有许可证的 iPhone 模拟器上测试

ios - UICollectionViewCell 以固有大小展开/折叠

ios - 如何更改 UICollectionView 中某个部分的背景颜色?