UICollectionViewCell用内在大小展开/折叠

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

按着这些次序:

1)。 创build一个名为isExpanded的布尔variables来pipe理展开/折叠

2.)添加一个目标和动作到显示更多button

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

3.)在用于pipe理高度的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]; 

)build立和运行

以前的回应是好的,但如果你想要一些animation,你需要做这三个步骤:

1.使你的collectionViewLayout无效

 self.collectionView.collectionViewLayout.invalidateLayout() 

2.重新加载所需的indexPath或performBatchUpdates块内的所有数据

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

3.返回sizeForItemAtIndexpath委托方法中计算的新高度