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

如何解决SwiftUI过渡中添加/移除视图时的异常跳动动画问题?

解决SwiftUI中VStack元素过渡时的跳动问题

问题出在你给整个VStack绑定了基于myArray.count的动画,这会让VStack的整体布局变化也参与动画,和元素自身的scale过渡叠加后就产生了跳动。要解决这个问题,需要将容器的布局更新和元素的过渡动画分离:

  1. 移除VStack上的全局动画,避免容器布局参与动画
  2. 在修改数组的操作中,用withAnimation包裹,让元素的过渡动画单独生效

修改后的完整代码如下:

import Cocoa
import SwiftUI

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.wantsLayer = true
        self.view = NSHostingView(rootView: ContentView())
    }

}

struct ContentView: View {
    
    @State private var myArray: [CustomType] = [CustomType(1), CustomType(2), CustomType(3), CustomType(4), CustomType(5)]
    
    var body: some View {
        
        VStack(spacing: 20) {
            
            ForEach(myArray, id:\.id) { item in
                
                Circle()
                    .fill(Color.red)
                    .frame(width: 100.0, height: 100.0)
                    .overlay(content: {
                        Text(String(describing: item.value))
                            .font(Font.system(.largeTitle, design: .monospaced))
                    })
                    .transition(AnyTransition.scale)
                
            }
            
            Button("add") {
                withAnimation(.linear(duration: 0.2)) {
                    myArray.append(CustomType(myArray.count + 1))
                }
            }
            
            Button("remove") {
                guard myArray.count > 0 else { return }
                withAnimation(.linear(duration: 0.2)) {
                    myArray.removeLast()
                }
            }
        }
        .padding(30)
    }
    
    struct CustomType: Identifiable {
        
        let id: UUID = UUID()
        var value: Int
        
        init(_ value: Int) {
            self.value = value
        }
        
    }
}

这样修改后,添加或移除Circle时,只有元素会执行scale过渡动画,VStack的布局会直接更新,不会出现上下跳动的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 23:17:29