UICollectionViewCell expand/collapse with intrinsic size

后端 未结 2 843
野趣味
野趣味 2020-12-31 15:07

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 o

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-31 15:19

    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

提交回复
热议问题