方法一:(會有副作用)
[_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:index] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
headerView不顯示了,被上方搜索框擋住了。
somebody可能說讓header懸浮可以解決,於是我們設置layout的sectionHeadersPinToVisibleBounds 屬性
注意:sectionHeadersPinToVisibleBounds 是UICollectionViewFlowLayout的屬性,不是collectionView的屬性。
從圖中可以看出,header遮擋住cell了,顯然效果依然不好。所以方法一是有局限性的,如果只是一組,指定滾動某個cell可以滿足需求。
方法二:
UICollectionViewLayoutAttributes *attributes = [_collectionView layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index]]; CGRect rect = attributes.frame; [_collectionView setContentOffset:CGPointMake(_collectionView.frame.origin.x, rect.origin.y - “header的高度”) animated:YES];
效果圖:
======================================================================
CollectionView在初始化的時候移動到某個距離
#pragma mark -- 使用場景:選中非第一張圖片用CollectionView進行瀏覽時,CollectionView滑動到相應的位置
#pragma mark -- 重點在於UICollectionViewFlowLayout的prepareLayout方法的使用 #pragma mark -- 自定義UICollectionViewFlowLayout的h文件 @interface SSCollectionViewFlowLayout : UICollectionViewFlowLayout //collectionView的偏移量 @property (nonatomic, assign) CGPoint offsetpoint; @end #pragma mark -- 自定義UICollectionViewFlowLayout的m文件 @implementation SSCollectionViewFlowLayout - (instancetype)init{ self = [super init]; if (self) { self.scrollDirection = UICollectionViewScrollDirectionHorizontal; } return self; } - (void)prepareLayout{ [super prepareLayout]; self.collectionView.contentOffset = self.offsetpoint; } - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)oldBounds{ return NO; } #pragma mark -- 剩下的工作就是在UICollectionView 所在的ViewController設置偏移量 @property (nonatomic, strong) SSCollectionViewFlowLayout *viewLayout; @property (nonatomic, strong) UICollectionView *ssCollectionView; - (void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; self.ssCollectionView.frame = CGRectMake(0.f, 0.f, ScreenWidth, ScreenHeight); self.viewLayout.offsetpoint = CGPointMake(ScreenWidth *self.indexNumber, 0.f); } - (UICollectionView *)ssCollectionView{ if (_ssCollectionView != nil) { return _ssCollectionView; } self.viewLayout = [[SSCollectionViewFlowLayout alloc] init]; _ssCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.viewLayout]; _ssCollectionView.showsHorizontalScrollIndicator = FALSE; // 去掉滾動條 _ssCollectionView.pagingEnabled = YES; _ssCollectionView.delegate = self; _ssCollectionView.dataSource = self; [_ssCollectionView registerClass:[CustomCollectionViewCell class] forCellWithReuseIdentifier:@"CollectionCell"]; return _ssCollectionView; }