#5 ScrollViewReader

功能

ScrollViewReader 不是滚动容器,而是 只负责"滚动导航" 的视图包装器。它生成一个 proxy,供内部代码调用 scrollTo(id, anchor:) 将任意子项瞬间或动画地滚动到可见区域。

核心 API

swift 复制代码
proxy.scrollTo<ID>(
    id,           // 与子项 .id 同类型
    anchor: .top  // 可选,目标对齐位置
)
  • 不返回任何值;若 id 不存在静默忽略。
  • 必须包在 withAnimation 内才能产生平滑滚动。

示例

swift 复制代码
struct ScrollViewReaderBootcamp: View {
    
    @State var textFieldText: String = ""
    @State var scrollToIndex: Int = 0
    var body: some View {
        
        VStack {
            TextField("Enter a # here..", text: $textFieldText)
                .frame(height: 56)
                .border(.gray)
                .padding()
                .keyboardType(.numberPad)
            
            Button("SCROLL NOW") {
                withAnimation(.spring()) {
                    if let index = Int(textFieldText) {
                        scrollToIndex = index
                    }
                    
                    // anchor 就是目标元素最终的位置
//                    proxy.scrollTo(30, anchor: .top)
                }
            }
            
            ScrollView {
                ScrollViewReader { proxy in
                    ForEach(0..<50) { index in
                        Text("This is item \(index)")
                            .font(.headline)
                            .frame(height: 180)
                            .frame(maxWidth: .infinity)
                            .background(.white)
                            .cornerRadius(8)
                            .shadow(radius: 8)
                            .padding()
                            .id(index) // proxy.scrollTo 需要配合 .id() 使用
                    }
                    .onChange(of: scrollToIndex) { oldValue, newValue in
                        withAnimation(.spring()) {
                            proxy.scrollTo(newValue, anchor: .top)
                        }
                    }
                }
            }
        }
    }
}

与 ScrollView 的关系

  • ScrollViewReader 自身不滚动、不占位,仅提供控制句柄。
  • 一个 Reader 可包裹多个 ScrollView / List;每个 ScrollView 内部子项 id 唯一即可。
  • 支持横向滚动:使用 ScrollView(.horizontal) 即可,API 不变。

注意事项

  1. scrollTo 必须在 Reader 的闭包内调用,否则编译错误。
  2. 若 id 重复或缺失,滚动无效果且不报错,请保证数据范围正确。
  3. 键盘弹出、屏幕旋转等场景,可结合 GeometryReader 动态计算锚点,避免遮挡。
相关推荐
FairGuard手游加固6 小时前
iOS 游戏加固技术解析:代码混淆、资源加密、内存保护与重签名检测
安全·游戏·macos·unity·ios·objective-c
思盛iOS签名上架6 小时前
iOS企业签名原理是什么?
macos·ios·cocoa
Daniel_Coder7 小时前
我用 SwiftUI + GRDB 做了一个「按时吃药·服药提醒」App
ios·swiftui·swift·widgetkit
Patrick_Wilson9 小时前
iOS 第三方浏览器图片下载失败问题
前端·ios·浏览器
悟空瞎说1 天前
NSNotificationCenter(NotificationCenter)官方文档白话翻译 + API 详解 + Swift 实战
ios
末代iOS程序员华仔1 天前
iOS个人开发者账号申请为啥会被卡住
ios·swift·figma
MaoJiu1 天前
从纹理采样到局部形变:实时瘦鼻 Shader 算法解析
ios
奈斯先生Vector1 天前
从“能调用”到“可替换”:Coze 多模型 API 编排层设计指南
linux·运维·人工智能·ubuntu·平面·ios
DogDaoDao1 天前
HarmonyOS 深度解析:从微内核到 ArkTS 工程实战
android·linux·ios·华为·程序员·harmonyos·harmonyos next