Mar*_*les 19 iphone ios uicollectionview
下面的代码滚动到右边的单元格UICollectionView,但UINavigationBar在我的情况下隐藏了部分标题视图.我相信我应该使用scrollRectToVisible而我的问题是,CGRect当numberOfRows给定section的变量时,计算(y位置)的正确方法是什么.
- (void)scrollToPricing:(NSUInteger)row {
[self.collectionView scrollToItemAtIndexPath:
[NSIndexPath indexPathForItem:0
inSection:row]
atScrollPosition:UICollectionViewScrollPositionTop
animated:YES];
}
Run Code Online (Sandbox Code Playgroud)
pix*_*eak 16
似乎所有答案都过于复杂.这对我有用:
let attributes = self.collectionView.collectionViewLayout.layoutAttributesForSupplementaryViewOfKind(UICollectionElementKindSectionHeader, atIndexPath: NSIndexPath(forItem: 0, inSection: section))
self.collectionView.setContentOffset(CGPointMake(0, attributes!.frame.origin.y - self.collectionView.contentInset.top), animated: true)
Run Code Online (Sandbox Code Playgroud)
斯威夫特3:
if let attributes = collectionView.collectionViewLayout.layoutAttributesForSupplementaryView(ofKind: UICollectionElementKindSectionHeader, at: IndexPath(item: 0, section: section)) {
collectionView.setContentOffset(CGPoint(x: 0, y: attributes.frame.origin.y - collectionView.contentInset.top), animated: true)
}
Run Code Online (Sandbox Code Playgroud)
Sun*_*hah 11
我想这可能会对你有所帮助
UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForItemAtIndexPath:indexPath];
Run Code Online (Sandbox Code Playgroud)
然后你可以通过访问该位置 attributes.frame
首先,获取节中标题的框架:
- (CGRect)frameForHeaderForSection:(NSInteger)section {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:1 inSection:section];
UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForItemAtIndexPath:indexPath];
CGRect frameForFirstCell = attributes.frame;
CGFloat headerHeight = [self collectionView:_collectionView layout:_layout referenceSizeForHeaderInSection:section].height;
return CGRectOffset(frameForFirstCell, 0, -headerHeight);
}
Run Code Online (Sandbox Code Playgroud)
注:我只是把值1的indexPath.item.您可能需要将其更改为适合您的实现的内容.
然后,滚动UIScrollView到标题顶部的点:
- (void)scrollToTopOfSection:(NSInteger)section animated:(BOOL)animated {
CGRect headerRect = [self frameForHeaderForSection:section];
CGPoint topOfHeader = CGPointMake(0, headerRect.origin.y - _collectionView.contentInset.top);
[_collectionView setContentOffset:topOfHeader animated:animated];
}
Run Code Online (Sandbox Code Playgroud)
注意:您必须减去contentInset,否则它将被丢弃,您的滚动视图将滚动状态栏和/或导航栏后面.
根据@pixelfreak答案
Swift 4.2+ iOS 11 Safe Area支持(适用于iPhone X及更高版本)if let attributes = collectionView.layoutAttributesForSupplementaryElement(ofKind: UICollectionView.elementKindSectionHeader, at: IndexPath(item: 0, section: section)) {
var offsetY = attributes.frame.origin.y - collectionView.contentInset.top
if #available(iOS 11.0, *) {
offsetY -= collectionView.safeAreaInsets.top
}
collectionView.setContentOffset(CGPoint(x: 0, y: offsetY), animated: true) // or animated: false
}
Run Code Online (Sandbox Code Playgroud)
快乐编码
| 归档时间: |
|
| 查看次数: |
13597 次 |
| 最近记录: |