gpt4 book ai didi

ios - ScrollView didEndDragging 时预测可见索引路径

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:11:29 24 4
gpt4 key购买 nike

我有一个带有水平流布局和固定宽度单元格的 Collection View 。当用户结束拖动时,我想抢先获取在减速完成时可见的项目的内容。

为此,我需要在减速结束时可见的索引路径。我认为这段代码有效,但是很蹩脚(出于显而易见的原因,我认为,评论中只描述了其中的一些):

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
// already bummed here:
// a) this seems the wrong way to get the fixed cell width
// b) sad that this method precludes variable width cells
UICollectionViewLayoutAttributes *la = [self.collectionView.collectionViewLayout layoutAttributesForElementsInRect:self.collectionView.bounds][0];
CGFloat width = la.size.width;

// this must be wrong, too. what about insets, header views, etc?
NSInteger firstVisible = floorf(targetContentOffset->x / width);

NSInteger visibleCount = ceilf(self.collectionView.bounds.size.width / width);
NSInteger lastVisible = MIN(firstVisible+visibleCount, self.model.count);
NSMutableArray *willBeVisibleIndexPaths = [@[] mutableCopy];

// neglecting sections
for (NSInteger i=firstVisible; i<lastVisible; i++) {
[willBeVisibleIndexPaths addObject:[NSIndexPath indexPathForItem:i inSection:0]];
}
}

这是很多脆弱的代码来做一些看起来很简单的事情。如果我想让它处理部分、插图、辅助 View 、可变单元格等,它很快就会变成一个错误多多、效率低下的困惑局面。

请告诉我,我在 sdk 中遗漏了一些简单的东西。

最佳答案

我认为使用 UICollectionView indexPathForItemAtPoint: 方法会更好。

根据targetContentOffset和 Collection View 的contentSize计算 Collection View 可见区域的左上点和右下点。

然后利用这两个点得到对应的两个indexPath值。这将为您提供 firstVisiblelastVisible 索引路径。

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
UICollectionView *collectionView = (UICollectionView *)scrollView;
CGPoint topLeft = CGPointMake(targetContentOffset->x + 1, targetContentOffset->y + 1);
CGPoint bottomRight = CGPointMake(topLeft.x + scrollView.bounds.size.width - 2, topLeft.y + scrollView.bounds.size.height - 2);

NSIndexPath *firstVisible = [collectionView indexPathForItemAtPoint:topLeft];
firstVisible = (firstVisible)? firstVisible : [NSIndexPath indexPathForItem:0 inSection:0];
NSIndexPath *lastVisible = [collectionView indexPathForItemAtPoint:bottomRight];
lastVisible = (lastVisible)? lastVisible : [NSIndexPath indexPathForItem:self.model.count-1 inSection:0];

NSMutableArray *willBeVisibleIndexPaths = [@[] mutableCopy];
for (NSInteger i=firstVisible.row; i<lastVisible.row; i++) {
[willBeVisibleIndexPaths addObject:[NSIndexPath indexPathForItem:i inSection:0]];
}
}

这只是部分解决方案。很可能存在 lastVisiblenil 的情况。您需要检查它并将 lastVisible 设置为集合的最后一个 indexPath 应该是什么。 firstVisiblelastVisible 也可能是 nil,因为这些点位于页眉或页脚 View 中。

关于ios - ScrollView didEndDragging 时预测可见索引路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33636874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com