#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 动态计算锚点,避免遮挡。
相关推荐
HouWan1 小时前
SwiftUI 小技巧:如何读取 SwiftUI Font 的详细信息
ios·swiftui·apple
李游Leo1 小时前
HarmonyOS 7 实战开发 05:把页面做到可上线状态
ios·harmonyos
终端安全笔记7 小时前
描述文件、企业证书、MDM 不是三个名字,是三层
android·ios·智能手机
传奇开心果编程7 小时前
【SwiftUI入门练中学】第1课 从零开始
学习·ui·ios·swiftui·swift
丿Wayne13 小时前
iOS Token 刷新实战(Actor 避免并发重复刷新)
ios·swift·token·actor·swift并发
终端安全笔记1 天前
iOS 27 给了租赁一个新工具,但它只认受监督的设备
android·网络·安全·ios
大熊猫侯佩1 天前
独立 App 首发完成 iPhone Duo 展开态适配
ios·swiftui·swift
光影少年1 天前
setImmediate 和 setTimeout(0) 的区别
android·前端·react.js·ios·前端框架
2501_916008891 天前
SSE 和 gRPC 流式接口如何抓包,调试 SSE 与 gRPC 流式接口
网络协议·计算机网络·网络安全·ios·adb·https·udp