UICollectionViewCell 以固有大小展开/折叠 [英] UICollectionViewCell expand/collapse with intrinsic size

查看:17
本文介绍了UICollectionViewCell 以固有大小展开/折叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a collection view with a custom flow layout, and many different cells of different height. The width of the collection view changes on device rotation, so the width of cells must change accordingly. For this to work, I implemented "sizeForItemAtIndex" method, and return different sizes depending on current interface orientation. Most of the cells do not change their height, however, there is one cell that I want to expand and collapse whenever the user taps on it. You can assume that the cell only has one UILabel with one or more lines of text. When the cell appear for the first time the number of lines is set to 1, and when user taps on the cell the number of lines is set to 0, and here the cell should use the intrinsic size of the label to change it’s height automatically. How can I achieve this effect? Here is an example of what it should look like:

推荐答案

请按以下步骤操作:

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

1). Create a boolean variable named isExpanded to manage expand / collapse

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

2.) Add a target and action to the show more button

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

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

3.) In sizeForItemAtIndexPath for managing height, add:

 - (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 方法中

4.) Then in the ShowMoreButtonClicked method

- (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 中添加这一行

5.) Add this line in your cellForItemAtIndexPath

 [yourCellName layoutIfNeeded];

6.) 构建 &运行

6.) Build & run

这篇关于UICollectionViewCell 以固有大小展开/折叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆