当前位置: 首页 > news >正文

Swift 让ScrollView滚动到具体某个位置

1. 使用scrollToItem方法滚动集合视图

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {let firstIndexPath = IndexPath(item: 0, section: 0)let lastIndexPath = IndexPath(item: self.recordArray.count - 1, section: 0)// Scroll to first itemself.collectionView.scrollToItem(at: firstIndexPath, at: .left, animated: false)// Delay for a short time (e.g., 0.1 seconds)DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {// Scroll to last itemself.collectionView.scrollToItem(at: lastIndexPath, at: .left, animated: false)}
}

上述代码中,首先使用scrollToItem方法将集合视图滚动到第一条数据(左侧对齐),然后在稍后的延迟时间后,再次使用scrollToItem方法将其滚动到最后一条数据(左侧对齐)。

2. 使用setContentOffset方法来滚动集合视图

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {let firstIndexPath = IndexPath(item: 0, section: 0)let lastIndexPath = IndexPath(item: self.recordArray.count - 1, section: 0)if let firstCellAttributes = self.collectionView.layoutAttributesForItem(at: firstIndexPath),let lastCellAttributes = self.collectionView.layoutAttributesForItem(at: lastIndexPath) {let contentOffset = CGPoint(x: lastCellAttributes.frame.origin.x - firstCellAttributes.frame.origin.x,y: 0)self.collectionView.setContentOffset(contentOffset, animated: false)}
}

上述代码中,我们使用了setContentOffset方法来滚动集合视图。我们获取了第一条数据和最后一条数据的布局属性,然后根据它们的位置计算出正确的contentOffset值,使得集合视图能够滚动到最后一条数据。

3. 使用scrollRectToVisible方法进行滚动集合视图

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {let firstIndexPath = IndexPath(item: 0, section: 0)let lastIndexPath = IndexPath(item: self.recordArray.count - 1, section: 0)if let firstCellAttributes = self.collectionView.layoutAttributesForItem(at: firstIndexPath),let lastCellAttributes = self.collectionView.layoutAttributesForItem(at: lastIndexPath) {let firstRect = firstCellAttributes.framelet lastRect = lastCellAttributes.framelet visibleRect = CGRect(x: lastRect.origin.x, y: 0, width: self.collectionView.bounds.width, height: self.collectionView.bounds.height)self.collectionView.scrollRectToVisible(visibleRect, animated: false)}
}

在上述代码中,我们使用了scrollRectToVisible方法来滚动集合视图。我们获取了第一条数据和最后一条数据的布局属性,并根据它们的位置计算出一个可见的矩形区域,然后将该矩形区域滚动到可见范围内。

http://www.lryc.cn/news/97858.html

相关文章:

  • 【C语言day08】
  • 【并发编程】ThreadLocal
  • 如何提高自己的软件测试水平之bug定位
  • 发点实用的快捷键(mac
  • Android播放多媒体文件——播放音频
  • 存储重启后,ceph挂载信息没了,手动定位osd序号并挂载到对应磁盘操作流程、ceph查看不到osd信息处理方法
  • Linux学习之循环处理位置参数
  • NLP实战8:图解 Transformer笔记
  • Pytorch个人学习记录总结 玩俄罗斯方块の深度学习小项目
  • PuTTY连接服务器报错Connection refused
  • 11-3_Qt 5.9 C++开发指南_QSqlQuery的使用(QSqlQuery 是能执行任意 SQL 语句的类)
  • 神码ai火车头伪原创插件怎么用【php源码】
  • 13.Netty源码之Netty中的类与API
  • C# 如何检查数组列表中是否存在数组
  • AI课堂教学质量评估系统算法 yolov7
  • eventBus使用遇到的坑
  • ChatGPT应用|科大讯飞星火杯认知大模型场景创新赛开始报名了!
  • DM8 DSC备份还原
  • 【Docker--harbor私有仓库部署与管理】
  • 基于量子同态加密的安全多方凸包协议
  • MySQL案例——多表查询以及嵌套查询
  • AI 视频清晰化CodeFormer-Deepfacelab
  • TCP协议如何实现可靠传输
  • 万恶的Eclipse的使用
  • 文件上传--题目
  • 小程序创建
  • stable diffusion如何确保每张图的面部一致?
  • 保存Windows锁屏壁纸
  • 面向对象编程:深入理解内部类与抽象类的使用
  • linux安装oracle