如何解决SwiftUI过渡中添加/移除视图时的异常跳动动画问题?
解决SwiftUI中VStack元素过渡时的跳动问题
问题出在你给整个VStack绑定了基于myArray.count的动画,这会让VStack的整体布局变化也参与动画,和元素自身的scale过渡叠加后就产生了跳动。要解决这个问题,需要将容器的布局更新和元素的过渡动画分离:
- 移除VStack上的全局动画,避免容器布局参与动画
- 在修改数组的操作中,用
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
相关产品推荐
相关产品推荐

