ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

swiftui-ui-patterns - scrollview

swiftui-ui-patterns - scrollview ScrollView 与 Lazy 堆栈意图当需要自定义布局、混合内容或水平/基于网格的滚动时使用ScrollView搭配LazyVStack、LazyHStack或LazyVGrid。核心模式对类似聊天或自定义信息流的布局优先使用ScrollViewLazyVStack。对 chips、标签、头像和媒体条使用ScrollView(.horizontal)LazyHStack。对图标/媒体网格使用LazyVGrid尽可能优先使用自适应列。使用ScrollViewReader进行滚动到顶部/底部和基于锚点的跳转。对应固定在键盘上方的输入栏使用safeAreaInset(edge:)。示例垂直自定义信息流MainActorstructConversationView:View{privateenumConstants{staticletbottomAnchorbottom}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{scrollProxyproxy withAnimation{proxy.scrollTo(Constants.bottomAnchor,anchor:.bottom)}}}}}示例水平 chipsScrollView(.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会带来不必要的复杂性。
返回列表