如何从动画子视图中停止SwiftUI DragGesture

时间:2020-09-27 11:39:25

标签: swiftui draggesture

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

我曾考虑过传递带有@EnvironmentObject标志的isDragging,但是它的伸缩性不是很好(不适用于自定义的ButtonStyle s)

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())
    }
}


ui

更新:

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)

在现实生活中,容器包含一个按钮,该按钮的按下状态为动画

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

在子视图中添加了animationsDisabled函数,实际上该功能实际上阻止了子对象在拖动过程中移动。

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

有没有办法知道视图何时基本不移动/过渡?

3 个答案:

答案 0 :(得分:2)

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

无论如何...这是可行的解决方法-通过在中间注入其他托管控制器来破坏动画可见性。

通过Xcode 12 / iOS 14测试

demo

//@ assert positive_power_of_2 (1);  // Timeout
//@ assert positive_power_of_2 (2);  // Valid
//@ assert positive_power_of_2 (4);  // Valid
//@ assert !positive_power_of_2 (7); // Timeout

答案 1 :(得分:1)

这是我的最新答案。我不认为有什么不错的方法,所以现在我使用自定义按钮来实现它。

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来显式设置动画,我现在使用自定义Button和DragGesture来完成。

这是显式动画和隐式动画之间的区别。

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

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

答案 2 :(得分:1)

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动画,而value中的bottomState被更改。

此方法已使用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时才禁用动画,并且如果.animation(.spring())没有更改,动画bottomState应该总是可以工作。