SwiftUI中List内动画失效,需保留List特性求解决方案
SwiftUI List 内动画失效的解决办法
在Xcode 14.2中,List自带的视图复用机制会干扰过渡动画的执行,直接放置条件视图时动画会被吞掉。不想切换到LazyVStack的话,试试这几个方案:
方案1:给条件视图添加唯一ID
给需要执行动画的条件视图加上.id(showColor),强制List感知视图的状态变化,从而触发过渡动画。修改后的代码如下:
struct SomeView: View { @State var showColor = false var body: some View { List { if showColor { Color.green .frame(width: 200, height: 200) .transition(.scale) .id(showColor) // 关键:让List识别视图状态变化 } Button { withAnimation { showColor.toggle() } } label: { Text("show/hide color") } } } }
方案2:给List绑定动画触发值
如果涉及多个条件视图,也可以给整个List绑定动画触发值,让List在状态变化时统一执行动画:
struct SomeView: View { @State var showColor = false var body: some View { List { if showColor { Color.green .frame(width: 200, height: 200) .transition(.scale) } Button { showColor.toggle() } label: { Text("show/hide color") } } .animation(.easeInOut, value: showColor) // 绑定动画到状态值 } }
这两个方案都不会影响List的onMove、onDelete等专属功能,只是调整了视图的识别逻辑或动画触发时机,List的核心特性完全保留。
内容的提问来源于stack exchange,提问作者Vahagn Gevorgyan
相关产品推荐
相关产品推荐

