Project requirements: CollectionView at the top there is a scrollview composed of labels, click on the tab, let CollectionView scroll to the specified line, scroll collectionview automatically switch to the top of the specified label
The implementation method is as follows:
1. 保证collectionView全部加载完毕,我这里通过一个bool的标志位来标示
-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath { if([indexPath row] == ((NSIndexPath*)[[collectionView indexPathsForVisibleItems] lastObject]).row){ self.isLoaded = YES; } }
2. 标签点击了CollectionView滚动到指定行
if (self.isloaded) {Scroll to Selected indexnsindexpath* Cellindexpath = [Nsindexpath Indexpathforitem:0 insection:index+1];uicollectionviewlayoutattributes* attr = [ self.collectionview.collectionviewlayout layoutattributesforsupplementaryviewofkind: uicollectionelementkindsectionheader Atindexpath:cellindexpath]; uiedgeinsets insets = Self.collectionView.scrollIndicatorInsets; cgrect rect = attr.frame; rect.size = cgfloat offset = (RECT.ORIGIN.Y + rect.size.height)- Self.collectionView.contentSize.height; if (Offset > 0.0) rect = Cgrectoffset (rect, 0,-offset); [Weakself.collectionview scrollrecttovisible:rect animated:YES];}
3. CollectionView滚动到指定行的时候,同时切换标签滚动
-(void) Scrollviewdidscroll: (Uiscrollview *) scrollview{StaticNsinteger Currentindex =0;Nsinteger Index=scrollview.contentoffset.y;CGRect Visiblerect = (CGRect) {. origin =self.collectionview.contentoffset,. Size = Self.collectionView.bounds.size}; cgpoint visiblepoint = cgpointmake ( cgrectgetmidx (visiblerect), cgrectgetmidy (VisibleRect)) ; nsindexpath *visibleindexpath = [self.collectionView Indexpathforitematpoint:visiblepoint]; //NSLog (@ "%@", Visibleindexpath); if (currentindex = visibleindexpath.section | | visibleindexpath = nil" {return;} currentindex = Visibleindexpath.section; [self.itemtool itemscrolltopositionwithindex:currentindex isJump: yes]; }
Ioscollectioview the method to scroll to the specified section