我有一个横向UICollectionView
可以正常工作并滚动。当我点按某个项目时,我会更新我的数据并致电reloadData
。这有效,新数据显示在UICollectionView
中。
问题是滚动位置没有改变,它仍在查看最后一个位置。我想将滚动重置为顶部(或者在我的情况下左侧)。我怎么能这样做?
答案 0 :(得分:158)
你想要setContentOffset:
。它需要CGPoint作为参数,你可以使用CGPointMake设置你想要的东西,但如果你想回到集合的最开头,你可以简单地使用CGPointZero。
[collectionView setContentOffset:CGPointZero animated:YES];
答案 1 :(得分:30)
您可以使用此方法滚动到您想要的任何项目:
- (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath
atScrollPosition:(UICollectionViewScrollPosition)scrollPosition
animated:(BOOL)animated
答案 2 :(得分:18)
我经常在我的应用程序的不同部分使用它,所以我只是扩展了UIScrollView,因此它可以用于任何滚动视图和滚动视图子类:
extension UIScrollView {
/// Sets content offset to the top.
func resetScrollPositionToTop() {
self.contentOffset = CGPoint(x: -contentInset.left, y: -contentInset.top)
}
}
所以每当我需要重置位置时:
self.collectionView.resetScrollPositionToTop()
答案 3 :(得分:12)
在斯威夫特:
collectionView.setContentOffset(CGPointZero, animated: true)
如果您离开包含集合视图的视图,请在第二个视图控制器中进行更改,并在返回时需要更新集合视图:
@IBAction func unwindTo_CollectionViewVC(segue: UIStoryboardSegue) {
//Automatic table reload upon unwind
viewDidLoad()
collectionView.reloadData()
collectionView.setContentOffset(CGPointZero, animated: true)
}
在我的情况下,展开是很好的,因为viewDidLoad调用将更新CoreData上下文,reloadData调用将确保collectionView更新以反映新的CoreData上下文,然后contentOffset将确保表设置回顶部。
答案 4 :(得分:5)
CGPointZero在我的案例中转移了集合视图的内容,因为您没有计算内容插入。这对我有用:
CGPoint topOffest = CGPointMake(0,-self.collectionView.contentInset.top);
[self.collectionView setContentOffset:topOffest animated:YES];
答案 5 :(得分:4)
很抱歉,在撰写本文时我无法发表评论,但我使用的是UINavigationController,CGPointZero
本身并没有让我到达最顶层所以我不得不使用以下内容代替
CGFloat compensateHeight = -(self.navigationController.navigationBar.bounds.size.height+[UIApplication sharedApplication].statusBarFrame.size.height);
[self.collectionView setContentOffset:CGPointMake(0, compensateHeight) animated:YES];
希望这有助于将来的某些人。干杯!
答案 6 :(得分:3)
如果您查看控制器包含安全区域,请输入代码:
collectionView.setContentOffset(CGPointZero, animated: true)
无效,因此您可以使用通用扩展名:
extension UIScrollView {
func scrollToTop(_ animated: Bool) {
var topContentOffset: CGPoint
if #available(iOS 11.0, *) {
topContentOffset = CGPoint(x: -safeAreaInsets.left, y: -safeAreaInsets.top)
} else {
topContentOffset = CGPoint(x: -contentInset.left, y: -contentInset.top)
}
setContentOffset(topContentOffset, animated: animated)
}
}
答案 7 :(得分:2)
要处理UINavigationController
和透明导航栏,我必须计算额外的顶部偏移量以完美匹配第一个元素的位置。
Swift 1.1代码:
let topOffest = CGPointMake(0, -(self.collectionView?.contentInset.top ?? O))
self.collectionView?.setContentOffset(topOffest, animated: true)
干杯!
答案 8 :(得分:0)
在这种情况下,它可以工作- 在tableView的cellForRowAt函数中, let cell = //使用双端队列声明一个单元格 cell.myCollectionView.contentOffset = CGPoint(x:0,y:0)