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

SwiftUI中图片切换与移动动画异常问题问询

SwiftUI图片切换与移动动画异常修复

问题场景

使用如下SwiftUI代码时,图片切换与移动动画表现异常:图片未随整个视图平滑移动,而是先淡出再在目标位置淡入,动画过程缺乏连贯的过渡效果。

struct AnimationTestView: View {
    @State var selected: Bool = false
    
    var body: some View {
        HStack {
            if !selected {
                Image(systemName: "plus.circle")
                    .resizable()
                    .frame(width: 50, height: 50)
                    .background(Color.green)
            }
            
            Image(systemName: selected ? "plus.circle.fill" : "plus.circle")
                .resizable()
                .frame(width: 50, height: 50)
                .background(Color.yellow)
                .onTapGesture {
                    withAnimation {
                        selected.toggle()
                    }
                }
            Spacer()
        }
    }
}

解决方案

给第二个Image添加.drawingGroup()修饰符,即可让图片跟随视图平滑移动,实现预期的过渡动画效果。修改后的代码如下:

struct AnimationTestView: View {
    @State var selected: Bool = false
    
    var body: some View {
        HStack {
            if !selected {
                Image(systemName: "plus.circle")
                    .resizable()
                    .frame(width: 50, height: 50)
                    .background(Color.green)
            }
            
            Image(systemName: selected ? "plus.circle.fill" : "plus.circle")
                .resizable()
                .frame(width: 50, height: 50)
                .background(Color.yellow)
                .drawingGroup() // 添加此修饰符
                .onTapGesture {
                    withAnimation {
                        selected.toggle()
                    }
                }
            Spacer()
        }
    }
}

内容的提问来源于stack exchange,提问作者Wujo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 05:23:20