iOS UICollectionView 添加headerView分組后滾動到指定的section


方法一:(會有副作用)

[_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; }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM