当我们使用uicollectionview实现,无线轮播滚动时(整页滚动。可视区域只会显示一个item), 采用多个分区的形式, 每次滚动完之后,会无动画滚动到中间的分区,这样就实现了无线滚动的效果。
通过uiscrollview
的-scrollviewdidenddecelerating:
方法得到indexpath更新的时刻, 然后用[collectionview indexpathsforvisibleitems]
获取一组当前显示的cell们的indexpath的数组,和上面的方案一样,我只要取里面的第一个.
当我们采用上面两种方式,回去当前的显示cell
或则indexpath
时, 在我们快速手动滚动的时候, 虽然在视觉上看到只显示一个item, 但是实际上有时候我们获取是多个cell
或则indexpath
的情况,并且顺序是不一定的, 导致我们通过firstobject
或则lastobject
的方式获取的item可能是错误的, 导致滚动顺序错乱。注意:对获取之后的数组进行排序也是不可取的, 也会造成顺序错乱
解决方法:
// 监听uiscrollview的滑动停止
- (void)scrollviewdidenddecelerating:(uiscrollview *)scrollview {
// uicollectionview的宽度和cell宽度相等: 当手指快读滑动时, 有时indexpathsforvisibleitems() 获取的indexpath不一定只有一个cell,有时候会出现两个,而且顺序不一定正确。
nsindexpath *currentindexpath = [self.videocollectionview indexpathforitematpoint:self.videocollectionview.contentoffset];
if (currentindexpath && currentindexpath.row < self.datas.count) {
nsindexpath *currentindexpathreset = [nsindexpath indexpathforitem:currentindexpath.row insection:maxsection / 2];
[self.videocollectionview scrolltoitematindexpath:currentindexpathreset atscrollposition:uicollectionviewscrollpositionnone animated:no];
self.pagecontrol.currentindex = currentindexpathreset.row;
}
}
我们这里可以通过方法:- (nullable nsindexpath *)indexpathforitematpoint:(cgpoint)point;
通过指定坐标来获取当前正在显示的cell,该方法可以获取正在显示的item的nsindexpath
, 得到正确的下标。
发表评论