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方法来滚动集合视图。我们获取了第一条数据和最后一条数据的布局属性,并根据它们的位置计算出一个可见的矩形区域,然后将该矩形区域滚动到可见范围内。

相关推荐
superman超哥几秒前
仓颉语言中错误恢复策略的深度剖析与工程实践
c语言·开发语言·c++·python·仓颉
rchmin4 分钟前
Java内存模型(JMM)详解
java·开发语言
studytosky5 分钟前
Linux系统编程:深度解析 Linux 进程,从底层架构到内存模型
linux·运维·服务器·开发语言·架构·vim
陳10305 分钟前
C++:string(3)
开发语言·c++
Wpa.wk11 分钟前
Tomcat的安装与部署使用 - 说明版
java·开发语言·经验分享·笔记·tomcat
吧啦蹦吧16 分钟前
java.lang.Class#isAssignableFrom(Class<?> cls)
java·开发语言
都是蠢货24 分钟前
drop delete和truncate的区别?
java·开发语言
搬砖的kk35 分钟前
Lycium++ - OpenHarmony PC C/C++ 增强编译框架
c语言·开发语言·c++
再__努力1点1 小时前
【77】积分图像:快速计算矩形区域和核心逻辑
开发语言·图像处理·人工智能·python·算法·计算机视觉
Evand J1 小时前
【2026课题推荐】基于小波/互相关/FFT的卡尔曼滤波的轨迹估计,及MATLAB例程的运行结果
开发语言·matlab·目标跟踪·轨迹跟踪