轻按时如何将 UICollectionView 居中? [英] How to center a UICollectionView when it is tapped?
问题描述
我有一个 UICollectionView
,上面有很多 UICollectionViewCells
.我想在点击时将单元格滚动到 UICollectionView
的中心.我担心的是,即使我点击最后一个或顶部的单元格,它也应该移动到集合视图的中心.
I have a UICollectionView
and it has quite a lot of UICollectionViewCells
on it. I want to scroll the cell to the centre of the UICollectionView
when it is tapped. My concern is that even if I tap the last or the top cell it should move to the centre of the collection view.
我已尝试设置 contentInsets
和偏移量,但它们似乎不起作用.我想我必须在选择时更改内容大小,并在滚动开始时将其更改回原始大小.
I have tried setting the contentInsets
and offsets but they don't seem to work. I think I will have to change the content size on selection and change it back to original when the scrolling begins.
推荐答案
设置 contentInsets 应该在第一个和最后一个单元格周围留出一些额外的空间:
Setting contentInsets should give some extra space around first and last cells:
CGFloat collectionViewHeight = CGRectGetHeight(collectionView.bounds);
[collectionView
setContentInset:
UIEdgeInsetsMake(collectionViewHeight/2, 0, collectionViewHeight/2, 0) ];
// nb, those are top-left-bottom-right
你应该打电话后:
[collectionView scrollToItemAtIndexPath:selectedItemPath
atScrollPosition:UICollectionViewScrollPositionCenteredVertically
animated:YES];
传递正确的滚动位置很重要:UICollectionViewScrollPositionCenteredVertically
It's important to pass correct scroll position: UICollectionViewScrollPositionCenteredVertically
这应该正确地居中点击项目.
This should center tapped item properly.
编辑
真的很奇怪,但是设置 UIEdgeInsets 为集合视图方法 scrollToItemAtIndexPath 后不能正常工作,所以我做了一些修改:
It's really strange, but after setting UIEdgeInsets to collection view method scrollToItemAtIndexPath does not works properly, so i make some modification:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
CGFloat collectionViewHeight = CGRectGetHeight(self.collectionView.frame);
[collectionView setContentInset:UIEdgeInsetsMake(collectionViewHeight / 2, 0, collectionViewHeight / 2, 0)];
UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
CGPoint offset = CGPointMake(0, cell.center.y - collectionViewHeight / 2);
[collectionView setContentOffset:offset animated:YES];
}
对我来说很好用.
这篇关于轻按时如何将 UICollectionView 居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!