使用 UICollectionView 分組顯示圖片或文字,每個組都會有一個頭視圖/尾視圖。有這么一個需求:要求UICollectionView 在開始出現(xiàn)的時候,就滑動到某個組的 header 或 footer。
實(shí)際上,在 UICollectionView.h 中搜索,你會發(fā)現(xiàn)有一個 - (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated; 可惜這個方法是給 Item準(zhǔn)備的,并不適用于 headerView / footerView 經(jīng)過查找后,也沒有發(fā)現(xiàn)諸如:- (void)scrollToSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath 的方法
解決辦法
修改 UICollectionView 的 ContentOffset
dispatch_async(dispatch_get_main_queue(), ^{
CGFloat offsetY = [self.collectionView layoutAttributesForSupplementaryElementOfKind:UICollectionElementKindSectionHeader atIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]].frame.origin.y;
CGFloat contentInsetY = self.collectionView.contentInset.top;
CGFloat sectionInsetY = ((UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout).sectionInset.top;
[self.collectionView setContentOffset:CGPointMake(self.collectionView.contentOffset.x, offsetY - contentInsetY - sectionInsetY) animated:NO];
});