Search code examples
iosautolayoutuicollectionview

UICollectionViewCell expand/collapse with intrinsic size


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: enter image description here


Solution

  • Follow these steps:

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

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

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

    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.) 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.) Add this line in your cellForItemAtIndexPath

     [yourCellName layoutIfNeeded];
    

    6.) Build & run