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

相关推荐
HarderCoder5 分钟前
Swift 并发编程新选择:Mutex 保护可变状态实战解析
swift
我狸才不是赔钱货1 小时前
Python的“环境之殇”:从Venv到Conda的终极抉择
开发语言·python·conda
游戏开发爱好者81 小时前
iOS 26 iPhone 使用记录分析 多工具组合构建全方位设备行为洞察体系
android·ios·小程序·uni-app·cocoa·iphone·webview
努力进修1 小时前
Rust 语言入门基础教程:从环境搭建到 Cargo 工具链
开发语言·后端·rust
杯莫停丶6 小时前
设计模式之:模板模式
开发语言·设计模式
开发者小天6 小时前
调整为 dart-sass 支持的语法,将深度选择器/deep/调整为::v-deep
开发语言·前端·javascript·vue.js·uni-app·sass·1024程序员节
老猿讲编程7 小时前
C++中的奇异递归模板模式CRTP
开发语言·c++
汤姆yu9 小时前
基于python的化妆品销售分析系统
开发语言·python·化妆品销售分析
ScilogyHunter9 小时前
C语言标准库完全指南
c语言·开发语言
sali-tec9 小时前
C# 基于halcon的视觉工作流-章52-生成标定板
开发语言·图像处理·人工智能·算法·计算机视觉