#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 动态计算锚点,避免遮挡。
相关推荐
lancoff11 小时前
#6 GeometryReader
ios·swiftui
1024小神12 小时前
xcode多环境 Dev 、Debug 和 Release变量配置以及怎么切换不同环境
开发语言·macos·ios·swiftui·xcode·swift
2501_9159184112 小时前
iOS 应用如何防止破解?从逆向链路还原攻击者视角,构建完整的反破解工程实践体系
android·macos·ios·小程序·uni-app·cocoa·iphone
他们都不看好你,偏偏你最不争气13 小时前
【iOS】MVVM
macos·ios·objective-c·cocoa
2501_9160074713 小时前
iOS 应用上架流程的工程化拆解 从签名体系到提交审核的全过程管控
android·ios·小程序·https·uni-app·iphone·webview
良逍Ai出海13 小时前
Vibecoding 开发前,要怎么去写一份面向Ai的需求文档
人工智能·ios·web app
一殊酒13 小时前
【前端开发】Uniapp:Android/IOS云打包
android·ios·uni-app
2501_9159184113 小时前
构建可靠的 iOS 日志导出体系,从真机日志到系统行为的多工具协同实践
android·ios·小程序·https·uni-app·iphone·webview
2501_9159090613 小时前
没有 Mac 怎么上架 iOS 应用 跨平台团队的可行交付方案分析
android·macos·ios·小程序·uni-app·iphone·webview