#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 动态计算锚点,避免遮挡。
相关推荐
东坡肘子5 小时前
Swift 还让你 Excited 吗?-- 肘子的 Swift 周报 #141
人工智能·swiftui·swift
壹方秘境19 小时前
我用Go语言开发了一个跨平台的HTTPS抓包和调试工具
前端·后端·ios
初级代码游戏6 天前
easy Photo Clean公测版:快速清理iPhone照片 邀请公测
ios·iphone
库奇噜啦呼6 天前
【iOS】RunLoop学习
学习·ios
黑科技iOS上架6 天前
iOS应用周末提交什么情况算卡审
经验分享·ios
zzb15806 天前
ios基础-MVC-UIView
ios·mvc·cocoa
kingbal6 天前
Flutter:Flutter SDK版本管理工具FVM
android·flutter·ios·android-studio·window
他们都不看好你,偏偏你最不争气7 天前
【iOS】Runtime - Part 2 && 消息发送:缓存、查找与转发
macos·ios·objective-c·cocoa
大熊猫侯佩7 天前
WWDC26:SwiftUI 8 的 @State 全新“懒加载”机制与最佳实践
性能优化·swiftui·observable·懒加载·state·swift宏·实例初始化