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

相关推荐
vortex517 分钟前
探索 Shell:选择适合你的命令行利器 bash, zsh, fish, dash, sh...
linux·开发语言·bash·shell·dash
zzc92119 分钟前
MATLAB仿真生成无线通信网络拓扑推理数据集
开发语言·网络·数据库·人工智能·python·深度学习·matlab
HUN金克斯28 分钟前
C++/C函数
c语言·开发语言·c++
慢半拍iii29 分钟前
数据结构——F/图
c语言·开发语言·数据结构·c++
钢铁男儿31 分钟前
C# 表达式和运算符(表达式和字面量)
开发语言·c#
编程有点难34 分钟前
Python训练打卡Day43
开发语言·python·深度学习
m0_6371469340 分钟前
零基础入门 C 语言基础知识(含面试题):结构体、联合体、枚举、链表、环形队列、指针全解析!
c语言·开发语言·链表
LjQ20401 小时前
网络爬虫一课一得
开发语言·数据库·python·网络爬虫
你是狒狒吗1 小时前
TM中,return new TransactionManagerImpl(raf, fc);为什么返回是new了一个新的实例
java·开发语言·数据库