You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 14:40:29