防止 SwiftUI 动画覆盖嵌套的 withAnimation 块

goh*_*tis 3 ios swiftui swiftui-animation

我有一个带有可拖动组件(“Springy”文本)的屏幕,当它以非常突出的弹簧动画释放时会弹回。

有一些文本异步Timer传入(在本例中,使用 a ),我希望它在 Springy 标签平滑向上移动以为其腾出空间时很好地淡入。

示例代码截图

我向 VStack 添加了一个动画,当异步加载的文本淡入时,它会按照我想要的方式转换。但是,这会破坏“弹性”文本上的弹簧动画。

这里注释掉了一个动画,如果将 1 秒动画切换到异步加载的文本淡入的那个位置,但就在动画的开头,“弹性”文本会跳起来而不是向上滑动。

我怎样才能让两个动画按照我的意愿工作?

import SwiftUI
import Combine

class Store: ObservableObject {
    @Published var showSection: Bool = false
    
    private var cancellables: [AnyCancellable] = []
    
    init() {
        
        Timer
            .publish(every: 2, on: RunLoop.main, in: .common)
            .autoconnect()
            .map { _ in true}
            .assign(to: \.showSection,
                    on: self)
            .store(in: &cancellables)
    }
}

struct ContentView: View {
    
    @ObservedObject var store = Store()
    
    @State var draggedState = CGSize.zero
    
    var body: some View {
        VStack {
            Spacer()
            VStack(alignment: .leading) {
                VStack(spacing: 4) {
                    HStack {
                        Text("Springy")
                            .font(.title)
                        Image(systemName: "hand.point.up.left.fill")
                            .imageScale(.large)
                            
                    }
                    .offset(x: draggedState.width, y: draggedState.height)
                    .foregroundColor(.secondary)
                    .gesture(
                        DragGesture().onChanged { value in
                            draggedState = value.translation
                        }
                        .onEnded { value in
                            // How can this animation be fast without the other animation slowing it down?
                            withAnimation(Animation
                                            .interactiveSpring(response: 0.3,
                                                               dampingFraction: 0.1,
                                                               blendDuration: 0)) {
                                draggedState = .zero
                            }
                        }
                    )
                    
                    VStack {
                        if store.showSection {
                            Text("Something that animates in after loading asynchrously.")
                                .font(.body)
                                .padding()
                                .transition(.opacity)
                        }
                    }
                    // When the animation is here, it doesn't cancel out the spring animation, but the Springy text jumps up at the beginning of the animation instead of animating.
//                    .animation(.easeInOut(duration: 1))
                }
                // Animation here has desired effect for loading, but overrides the Springy release animation.
                .animation(.easeInOut(duration: 1))
            }
            Spacer()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .preferredColorScheme(.dark)
    }
}
Run Code Online (Sandbox Code Playgroud)

扩展的问题,基于 Asperi 的回答。

现在,假设我在这个 mainVStack中有多个元素,我想在它们进来时设置动画。

  1. 为我想要制作动画的每个部分添加一个单独的.animation修饰符是一个很好的解决方案value吗?

在下面的扩展示例中,这是具有以下内容的部分:

.animation(.easeInOut(duration: 1),
                       value: store.showSection)
.animation(.easeInOut(duration: 1),
                      value: store.somePossibleText)
.animation(.easeInOut(duration: 1),
                      value: store.moreInformation)
Run Code Online (Sandbox Code Playgroud)
  1. 我在这里使用 3 种方法来确定是否显示一个部分。Bool为了简单起见,我在最初的示例中使用了,但在我的真实场景中,我认为使用该String?方法而不是设置单独的Bool或检查空字符串最有意义。在动画方面使用它是否有缺点,或者那很好吗?考虑到 Asperi 的解决方案,它在本示例中似乎运行良好。

这是带有新修改的完整示例:

import SwiftUI
import Combine

class Store: ObservableObject {
    
    @Published var showSection: Bool = false
    @Published var somePossibleText: String = ""
    @Published var moreInformation: String?
    
    private var cancellables: [AnyCancellable] = []
    
    init() {
        
        Timer
            .publish(every: 2, on: RunLoop.main, in: .common)
            .autoconnect()
            .map { _ in true }
            .assign(to: \.showSection,
                    on: self)
            .store(in: &cancellables)
        
        Timer
            .publish(every: 3, on: RunLoop.main, in: .common)
            .autoconnect()
            .map { _ in "Something else loaded later" }
            .assign(to: \.somePossibleText,
                    on: self)
            .store(in: &cancellables)
        
        Timer
            .publish(every: 4, on: RunLoop.main, in: .common)
            .autoconnect()
            .map { _ in "More stuff loaded later" }
            .assign(to: \.moreInformation,
                    on: self)
            .store(in: &cancellables)
    }
}

struct ContentView: View {
    
    @ObservedObject var store = Store()
    
    @State var draggedState = CGSize.zero
    
    var body: some View {
        VStack {
            Spacer()
            VStack(alignment: .leading) {
                VStack(spacing: 4) {
                    HStack {
                        Text("Springy")
                            .font(.title)
                        Image(systemName: "hand.point.up.left.fill")
                            .imageScale(.large)
                    }
                    .offset(x: draggedState.width,
                            y: draggedState.height)
                    .foregroundColor(.secondary)
                    .gesture(
                        DragGesture().onChanged { value in
                            draggedState = value.translation
                        }
                        .onEnded { value in
                            // TODO: how can this animation be fast without the other one slowing it down?
                            withAnimation(Animation
                                            .interactiveSpring(response: 0.3,
                                                               dampingFraction: 0.1,
                                                               blendDuration: 0)) {
                                draggedState = .zero
                            }
                        }
                    )
                    
                    if store.showSection {
                        Text("Something that animates in after loading asynchrously.")
                            .font(.body)
                            .padding()
                            .transition(.opacity)
                    }
                    
                    if store.somePossibleText != "" {
                        Text(store.somePossibleText)
                            .font(.footnote)
                            .padding()
                            .transition(.opacity)
                    }
                    
                    if let moreInformation = store.moreInformation {
                        Text(moreInformation)
                            .font(.footnote)
                            .padding()
                            .transition(.opacity)
                    }
                }
                .animation(.easeInOut(duration: 1),
                           value: store.showSection)
                .animation(.easeInOut(duration: 1),
                           value: store.somePossibleText)
                .animation(.easeInOut(duration: 1),
                           value: store.moreInformation)
            }
            Spacer()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .preferredColorScheme(.dark)
    }
}
Run Code Online (Sandbox Code Playgroud)

Asp*_*eri 6

如果我正确理解了您的期望,那么将最后一个动画绑定到showSection值就足够了,如下所示

}
// Animation here has desired effect for loading, but overrides the Springy release animation.
.animation(.easeInOut(duration: 1), value: store.showSection)
Run Code Online (Sandbox Code Playgroud)

使用 Xcode 12 / iOS 14 测试。