【问题标题】:UICollectionViewCell expand/collapse with intrinsic sizeUICollectionViewCell 以固有大小展开/折叠
【发布时间】:2015-10-10 06:45:03
【问题描述】:

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

【问题讨论】:

  • 您能补充一下到目前为止您尝试过的内容以及获得的结果吗?

标签: ios autolayout uicollectionview


【解决方案1】:

按照以下步骤操作:

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.) 构建和运行

【讨论】:

  • 干得好,我昨晚才弄清楚这个问题并说“我明天会回答”然后繁荣,就在这里
  • 有没有办法让自动布局自动计算高度?
  • 是的,为单元格返回这个大小:- CGSize CellSize = [yourCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize withHorizo​​ntalFittingPriority:UILayoutPriorityDefaultHigh verticalFittingPriority:UILayoutPriorityDefaultLow];
【解决方案2】:

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

1.使您的 collectionViewLayout 无效

self.collectionView.collectionViewLayout.invalidateLayout()

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多