当前位置: 代码网 > it编程>App开发>苹果IOS > UICollectionView获取当前item的NSIndexPath问题

UICollectionView获取当前item的NSIndexPath问题

2024年07月28日 苹果IOS 我要评论
UICollectionView获取当前item的NSIndexPath问题

当我们使用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, 得到正确的下标。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com