☰
swiftui-ui-patterns - scrollview
2026/10/8 2:00:53 网站建设 项目流程

ScrollView 与 Lazy 堆栈

意图

当需要自定义布局、混合内容或水平/基于网格的滚动时,使用ScrollView搭配LazyVStack、LazyHStack或LazyVGrid。

核心模式

  • 对类似聊天或自定义信息流的布局,优先使用ScrollView+LazyVStack。
  • 对 chips、标签、头像和媒体条使用ScrollView(.horizontal)+LazyHStack。
  • 对图标/媒体网格使用LazyVGrid;尽可能优先使用自适应列。
  • 使用ScrollViewReader进行滚动到顶部/底部和基于锚点的跳转。
  • 对应固定在键盘上方的输入栏使用safeAreaInset(edge:)。

示例:垂直自定义信息流

@MainActorstructConversationView:View{privateenumConstants{staticletbottomAnchor="bottom"}@StateprivatevarscrollProxy:ScrollViewProxy?varbody:someView{ScrollViewReader{proxyinScrollView{LazyVStack{ForEach(messages){messageinMessageRow(message:message).id(message.id)}Color.clear.frame(height:1).id(Constants.bottomAnchor)}.padding(.horizontal,.layoutPadding)}.safeAreaInset(edge:.bottom){MessageInputBar()}.onAppear{scrollProxy=proxy withAnimation{proxy.scrollTo(Constants.bottomAnchor,anchor:.bottom)}}}}}

示例:水平 chips

ScrollView(.horizontal,showsIndicators:false){LazyHStack(spacing:8){ForEach(chips){chipinChipView(chip:chip)}}}

示例:自适应网格

letcolumns=[GridItem(.adaptive(minimum:120))]ScrollView{LazyVGrid(columns:columns,spacing:8){ForEach(items){iteminGridItemView(item:item)}}.padding(8)}

应保留的设计选择

  • 当条目数量大或未知时,使用Lazy*堆栈。
  • 对数量少、固定大小的内容使用非懒加载堆栈,避免懒加载开销。
  • 使用ScrollViewReader时保持 ID 稳定。
  • 滚动到某个 ID 时优先使用显式动画(withAnimation)。

陷阱

  • 避免嵌套同轴的滚动视图;这会导致手势冲突。
  • 没有明确理由时,不要在同一层级中组合List和ScrollView。
  • 对微小的内容过度使用LazyVStack会带来不必要的复杂性。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询