ios - UICollectionViewCell expand/collapse with intrinsic size -


i have collection view custom flow layout, , many different cells of different height. width of collection view changes on device rotation, width of cells must change accordingly. work, implemented “sizeforitematindex” method, , return different sizes depending on current interface orientation. of cells not change height, however, there 1 cell want expand , collapse whenever user taps on it. can assume cell has 1 uilabel 1 or more lines of text. when cell appear first time number of lines set 1, , when user taps on cell number of lines set 0, , here cell should use intrinsic size of label change it’s height automatically. how can achieve effect? here example of should like: enter image description here

follow these steps:

1). create boolean variable named isexpanded manage expand / collapse

2.) add target , action show more button

[yourcellname.btnshowmore addtarget:self action:@selector(showmorebuttonclicked) forcontrolevents:uicontroleventtouchupinside]; 

3.) in sizeforitematindexpath 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 expanded cell);     }    return cgsizemake(cgrectgetwidth(self.view.frame), default height); } 

4.) in 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 line in cellforitematindexpath

 [yourcellname layoutifneeded]; 

6.) build & run


Comments