UICollectionViewCell使用固有大小扩展/折叠 [英] UICollectionViewCell expand/collapse with intrinsic size

查看:215
本文介绍了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天全站免登陆