如何阻止 SwiftUI DragGesture 对子视图进行动画处理

How to stop SwiftUI DragGesture from animating subviews

我正在构建一个自定义模态框,当我拖动模态框时,任何附加了动画的子视图都会在我拖动时进行动画处理。我该如何阻止这种情况发生?

我考虑过传递带有 isDragging 标志的 @EnvironmentObject,但它的可扩展性不是很好(并且不适用于自定义 ButtonStyles)

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .padding()
            .showModal(isShowing: .constant(true))
    }
}

extension View {
    func showModal(isShowing: Binding<Bool>) -> some View {
        ViewOverlay(isShowing: isShowing, presenting: { self })
    }
}

struct ViewOverlay<Presenting>: View where Presenting: View {
    @Binding var isShowing: Bool
    
    let presenting: () -> Presenting
    
    @State var bottomState: CGFloat = 0
    
    var body: some View {
        ZStack(alignment: .center) {
            presenting().blur(radius: isShowing ? 1 : 0)
            VStack {
                if isShowing {
                    Container()
                        .background(Color.red)
                        .offset(y: bottomState)
                        .gesture(
                            DragGesture()
                                .onChanged { value in
                                    bottomState = value.translation.height
                                }
                                .onEnded { _ in
                                    if bottomState > 50 {
                                        withAnimation {
                                            isShowing = false
                                        }
                                    }
                                    bottomState = 0
                                })
                        .transition(.move(edge: .bottom))
                }
            }
        }
    }
}

struct Container: View {
    var body: some View {
// I want this to not animate when dragging the modal
        Text("CONTAINER")
            .frame(maxWidth: .infinity, maxHeight: 200)
            .animation(.spring())
    }
}


更新:

extension View {
    func animationsDisabled(_ disabled: Bool) -> some View {
        transaction { (tx: inout Transaction) in
            tx.animation = tx.animation
            tx.disablesAnimations = disabled
        }
    }
}


Container()
   .animationsDisabled(isDragging || bottomState > 0)

在现实生活中,Container 包含一个按钮,其按下状态有一个动画

struct MyButtonStyle: ButtonStyle {
    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .scaleEffect(configuration.isPressed ? 0.9 : 1)
            .animation(.spring())
    }
}

向子视图添加了 animationsDisabled 函数,这实际上会阻止子视图在拖动过程中移动。

它不会在最初滑入或关闭时停止动画。

有没有办法知道视图何时基本上没有移动/转换?

所以这是我更新的答案。我不认为有一个很好的方法来做到这一点,所以现在我用自定义按钮来做。

import SwiftUI

struct ContentView: View {
    @State var isShowing = false
    var body: some View {
        Text("Hello, world!")
            .padding()
            .onTapGesture(count: 1, perform: {
                withAnimation(.spring()) {
                    self.isShowing.toggle()
                }
            })
            .showModal(isShowing: self.$isShowing)
    }
}

extension View {
    func showModal(isShowing: Binding<Bool>) -> some View {
        ViewOverlay(isShowing: isShowing, presenting: { self })
    }
}

struct ViewOverlay<Presenting>: View where Presenting: View {
    @Binding var isShowing: Bool
    
    let presenting: () -> Presenting
    
    @State var bottomState: CGFloat = 0
    @State var isDragging = false
    var body: some View {
        ZStack(alignment: .center) {
            presenting().blur(radius: isShowing ? 1 : 0)
            VStack {
                if isShowing {
                    Container()
                        .background(Color.red)
                        .offset(y: bottomState)
                        .gesture(
                            DragGesture()
                                .onChanged { value in
                                    isDragging = true
                                    bottomState = value.translation.height
                                    
                                }
                                .onEnded { _ in
                                    isDragging = false
                                    if bottomState > 50 {
                                        withAnimation(.spring()) {
                                            isShowing = false
                                        }
                                    }
                                    bottomState = 0
                                })
                        .transition(.move(edge: .bottom))
                }
            }
        }
    }
}

struct Container: View {
    var body: some View {
        CustomButton(action: {}, label: {
            Text("Pressme")
        })
        .frame(maxWidth: .infinity, maxHeight: 200)
    }
}

struct CustomButton<Label >: View where Label: View {
    @State var isPressed = false
    var action: () -> ()
    var label: () -> Label
    var body: some View {
        label()
            .scaleEffect(self.isPressed ? 0.9 : 1.0)
        .gesture(DragGesture(minimumDistance: 0).onChanged({_ in
            withAnimation(.spring()) {
                self.isPressed = true
            }
        }).onEnded({_ in
            withAnimation(.spring()) {
                self.isPressed = false
                action()
            }
        }))
    }
}

问题是您不能在容器内使用隐式动画,因为它们会在容器移动时进行动画处理。因此,您还需要使用 withAnimation 为按下的按钮显式设置动画,我现在使用自定义按钮和 DragGesture 来完成。

显式动画和隐式动画的区别

观看详细探讨此主题的视频:

https://www.youtube.com/watch?v=3krC2c56ceQ&list=PLpGHT1n4-mAtTj9oywMWoBx0dCGd51_yG&index=11

理论上 SwiftUI 不应在这种情况下转换动画,但我不确定这是否是一个错误 - 我不会以这种通用方式在 Container 中使用动画。我使用动画越多,就越倾向于将它们直接连接到特定值。

无论如何...这里有一个可能的解决方法 - 通过在中间注入不同的托管控制器来破坏动画可见性。

测试 Xcode 12 / iOS 14

struct ViewOverlay<Presenting>: View where Presenting: View {
    @Binding var isShowing: Bool
    
    let presenting: () -> Presenting
    
    @State var bottomState: CGFloat = 0
    
    var body: some View {
        ZStack(alignment: .center) {
            presenting().blur(radius: isShowing ? 1 : 0)
            VStack {
                    Color.clear
                if isShowing {
                        HelperView {
                    Container()
                        .background(Color.red)
                        }
                        .offset(y: bottomState)
                        .gesture(
                             DragGesture()
                                  .onChanged { value in
                                        bottomState = value.translation.height
                                  }
                                  .onEnded { _ in
                                        if bottomState > 50 {
                                             withAnimation {
                                                  isShowing = false
                                             }
                                        }
                                        bottomState = 0
                                  })
                        .transition(.move(edge: .bottom))
                }
                    Color.clear
            }
        }
    }
}

struct HelperView<Content: View>: UIViewRepresentable {
    let content: () -> Content
    func makeUIView(context: Context) -> UIView {
        let controller = UIHostingController(rootView: content())
        return controller.view
    }
    
    func updateUIView(_ uiView: UIView, context: Context) {
    }
}

Container 中,声明一个绑定变量,以便您可以将 bottomState 传递给 Container 视图:

struct Container: View {
    
    @Binding var bottomState: CGFloat

              .
              .
              .
              .
}

不要忘记将 bottomState 传递给您的 Container 视图:

Container(bottomState: $bottomState)

现在在您的 Container 视图中,您只需要在 bottomState 被更改时声明您不需要动画:

Text("CONTAINER")
            .frame(maxWidth: .infinity, maxHeight: 200)
            .animation(nil, value: bottomState) // You Need To Add This
            .animation(.spring())

.animation(nil, value: bottomState) 中,nil 您要求 SwiftUI 提供 no 动画,而 bottomStatevalue 正在更改。

此方法已使用 Xcode 12 GM、iOS 14.0.1 进行测试。 您必须按照我放置的顺序使用 Text 的修饰符。这意味着这将起作用:

.animation(nil, value: bottomState)
.animation(.spring())

但这行不通:

.animation(.spring())
.animation(nil, value: bottomState)

我还确保添加 .animation(nil, value: bottomState) 只会在 bottomState 被更改时禁用动画,如果 bottomState 未被更改,动画 .animation(.spring()) 应该始终有效改变了。