具有固有大小的 UICollectionViewCell expand/collapse

UICollectionViewCell expand/collapse with intrinsic size

我有一个带有自定义流布局的集合视图,以及许多不同高度的不同单元格。集合视图的宽度随设备旋转而变化,因此单元格的宽度必须相应地变化。为此,我实施了“sizeForItemAtIndex”方法,并根据当前界面方向 return 不同的尺寸。 大多数单元格不会改变它们的高度,但是,有一个单元格我想在用户点击它时展开和折叠。您可以假设单元格只有一个带有一行或多行文本的 UILabel。当单元格第一次出现时,行数设置为 1,当用户点击单元格时,行数设置为 0,此时单元格应使用标签的固有大小自动更改其高度.我怎样才能达到这种效果? 这是它应该是什么样子的示例:

按照以下步骤操作:

1).创建一个名为 isExpanded 的布尔变量来管理展开/折叠

2.) 向显示更多按钮添加目标和操作

[yourCellName.btnShowMore addTarget:self action:@selector(ShowMoreButtonClicked) forControlEvents:UIControlEventTouchUpInside];

3.) 在管理高度的sizeForItemAtIndexPath中,添加:

 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{

if (isExpanded && indexPath.row == 0) {
        return CGSizeMake(CGRectGetWidth(self.view.frame), calculated height for the expanded cell);
    }
   return CGSizeMake(CGRectGetWidth(self.view.frame), default height);
}

4.) 然后在 ShowMoreButtonClicked 方法中

- (void)ShowMoreButtonClicked{
    if (isExpanded) {
       isExpanded = FALSE;
       [collection_viewCus reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]]];

    }
    else {
       isExpanded = TRUE;
       [collection_viewCus reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]]];
   }}

5.) 在您的 cellForItemAtIndexPath 中添加这一行

 [yourCellName layoutIfNeeded];

6.) 构建 & 运行

之前的反应很好,但是如果你想要一些动画,你需要做这三个步骤:

1.Invalidate 你的 collectionViewLayout

self.collectionView.collectionViewLayout.invalidateLayout()

2.Reload 所需的 indexPath 或 performBatchUpdates 块中的所有数据

collectionView.performBatchUpdates({
            self.collectionView.reload(at: DESIRED_INDEXPATH)
        }, completion: nil)

3.Return在sizeForItemAtIndexpath委托方法中计算的新高度