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

  1. 使用scrollToItem方法滚动集合视图
Swift 复制代码
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 item
    self.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 item
        self.collectionView.scrollToItem(at: lastIndexPath, at: .left, animated: false)
    }
}

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

  1. 使用setContentOffset方法来滚动集合视图
Swift 复制代码
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值,使得集合视图能够滚动到最后一条数据。

  1. 使用scrollRectToVisible方法进行滚动集合视图
Swift 复制代码
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.frame
        let lastRect = lastCellAttributes.frame
        let 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方法来滚动集合视图。我们获取了第一条数据和最后一条数据的布局属性,并根据它们的位置计算出一个可见的矩形区域,然后将该矩形区域滚动到可见范围内。

相关推荐
dme.5 分钟前
Javascript之DOM操作
开发语言·javascript·爬虫·python·ecmascript
teeeeeeemo10 分钟前
回调函数 vs Promise vs async/await区别
开发语言·前端·javascript·笔记
加油吧zkf14 分钟前
AI大模型如何重塑软件开发流程?——结合目标检测的深度实践与代码示例
开发语言·图像处理·人工智能·python·yolo
ejinxian30 分钟前
PHP 超文本预处理器 发布 8.5 版本
开发语言·php
软件黑马王子1 小时前
C#系统学习第八章——字符串
开发语言·学习·c#
阿蒙Amon1 小时前
C#读写文件:多种方式详解
开发语言·数据库·c#
Da_秀1 小时前
软件工程中耦合度
开发语言·后端·架构·软件工程
Fireworkitte1 小时前
Java 中导出包含多个 Sheet 的 Excel 文件
java·开发语言·excel
瓜子三百克2 小时前
CALayer的异步处理
macos·ios·cocoa
运器1232 小时前
【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
开发语言·人工智能·python·算法·ai·散列表·ai编程