问题描述
我的应用程序中有一个非常简单的collectionView(只有一行方形缩略图)。
I've got a very simple collectionView in my app (just a single row of square thumbnail images).
我想拦截滚动,以便偏移始终在左侧留下完整图像。目前它滚动到任何地方并将留下截止的图像。
I'd like to intercept the scrolling so that the offset always leaves a full image at the left side. At the moment it scrolls to wherever and will leave cut off images.
无论如何,我知道我需要使用该功能
Anyway, I know I need to use the function
- (CGPoint)targetContentOffsetForProposedContentOffset:withScrollingVelocity
to这样做但我只是使用标准的 UICollectionViewFlowLayout
。我不是它的子类。
to do this but I'm just using a standard UICollectionViewFlowLayout
. I'm not subclassing it.
有没有任何方法可以在没有子类化的情况下拦截这个 UICollectionViewFlowLayout
?
Is there any way of intercepting this without subclassing UICollectionViewFlowLayout
?
谢谢
推荐答案
好的,答案是否定的,没有办法做到这一点没有子类化UICollectionViewFlowLayout。
OK, answer is no, there is no way to do this without subclassing UICollectionViewFlowLayout.
然而,对于将来阅读此内容的人来说,子类化非常容易。
However, subclassing it is incredibly easy for anyone who is reading this in the future.
首先我设置子类调用 MyCollectionViewFlowLayout
然后在界面构建器中我将集合视图布局更改为自定义并选择了我的流布局子类。
First I set up the subclass call MyCollectionViewFlowLayout
and then in interface builder I changed the collection view layout to Custom and selected my flow layout subclass.
因为你这样做你不能在IB中指定项目大小等...所以在MyCollectionViewFlowLayout.m我有这个......
Because you're doing it this way you can't specify items sizes, etc... in IB so in MyCollectionViewFlowLayout.m I have this...
- (void)awakeFromNib
{
self.itemSize = CGSizeMake(75.0, 75.0);
self.minimumInteritemSpacing = 10.0;
self.minimumLineSpacing = 10.0;
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
self.sectionInset = UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0);
}
这为我设置了所有尺寸和滚动方向。
This sets up all the sizes for me and the scroll direction.
然后......
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
CGFloat offsetAdjustment = MAXFLOAT;
CGFloat horizontalOffset = proposedContentOffset.x + 5;
CGRect targetRect = CGRectMake(proposedContentOffset.x, 0, self.collectionView.bounds.size.width, self.collectionView.bounds.size.height);
NSArray *array = [super layoutAttributesForElementsInRect:targetRect];
for (UICollectionViewLayoutAttributes *layoutAttributes in array) {
CGFloat itemOffset = layoutAttributes.frame.origin.x;
if (ABS(itemOffset - horizontalOffset) < ABS(offsetAdjustment)) {
offsetAdjustment = itemOffset - horizontalOffset;
}
}
return CGPointMake(proposedContentOffset.x + offsetAdjustment, proposedContentOffset.y);
}
这可以确保滚动结束时左边缘的边距为5.0 。
This ensures that the scrolling ends with a margin of 5.0 on the left hand edge.
这就是我需要做的全部。我根本不需要在代码中设置流程布局。
That's all I needed to do. I didn't need to set the flow layout in code at all.
这篇关于targetContentOffsetForProposedContentOffset:withScrollingVelocity,没有子类化UICollectionViewFlowLayout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!