UICollectionViewCell expands / collapses with internal size

I have a collection view with a custom flow layout and many different cells of different heights. The width of the collection view changes as the device rotates, so the width of the cells should change accordingly. To do this, I applied the sizeForItemAtIndex method and returned different sizes depending on the current orientation of the interface. Most cells do not change their height, but there is one cell that I want to expand and collapse when the user clicks on it. You can assume that a cell has only one UILabel with one or more lines of text. When the cell appears for the first time, the number of lines is 1, and when the user clicks on the cell, the number of lines is set to 0, and here the cell should use the internal size of the label to automatically change its height. How can I achieve this effect? Here is an example of how it should look: enter image description here

+8
ios autolayout uicollectionview
source share
2 answers

Follow these steps:

one). Create a boolean variable named isExpanded to control extension / failure

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

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

3.) In sizeForItemAtIndexPath for height control 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 to your cellForItemAtIndexPath

  [yourCellName layoutIfNeeded]; 

6.) Create and run

+11
source share

The previous answer is good, but if you need animation, you need to follow these three steps:

1.Don't go around your ViewLayout collection

 self.collectionView.collectionViewLayout.invalidateLayout() 

2. Load the desired index element or all data inside the executeBatchUpdates block

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

3. Change the new height calculated in the sizeForItemAtIndexpath delegate method

+1
source share

All Articles