UICollectionViewCell expand/collapse with intrinsic size

后端 未结 2 836
野趣味
野趣味 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

    0 讨论(0)
  • 2020-12-31 15:20

    The previous response is good but if you want some animation you need to do this three steps:

    1.Invalidate your collectionViewLayout

    self.collectionView.collectionViewLayout.invalidateLayout()
    

    2.Reload desired indexPath or all the data inside a performBatchUpdates block

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

    3.Return the new height calculated in sizeForItemAtIndexpath delegate method

    0 讨论(0)
提交回复
热议问题