如何在 SwiftUI 中使用动画重新创建平移手势

问题描述

这是我的带有动画的 UIPanGestureRecognizer 方法

@IBOutlet weak var constraintBottomSwipe: NSLayoutConstraint!
let generator = UIImpactFeedbackGenerator(style: .heavy)

func pullViewUp(with pan:UIPanGestureRecognizer) {
        let heightThreshold: CGFloat = 100
        func animateBack() {
            UIView.animate(withDuration: 0.4,delay: 0,usingSpringWithdamping: 1,initialSpringVeLocity: 0,options: .curveEaSEOut,animations: {
                self.constraintBottomSwipe.constant = 90
                self.view.layoutIfNeeded()
            })
        }

        let yTranslation = pan.translation(in: self.view).y
        let distance = CGFloat(sqrt( Double(-yTranslation) ))
        let newHeight = constraintBottomSwipe.constant + distance
        if pan.state == .began {
            generator.prepare()
        }
        
        if pan.state == .changed {
            guard !newHeight.isNaN else {
                animateBack()
                return
            }

            constraintBottomSwipe.constant = newHeight
            pan.setTranslation(.zero,in: view)
            
            if newHeight > heightThreshold,!willdismiss {
                willdismiss = true
            } else if willdismiss,newHeight < heightThreshold {
                willdismiss = false
            }
        }

        if pan.state == .ended,willdismiss {
            // custom action here.
        } else {
            if pan.state == UIPanGestureRecognizer.State.ended {
                pan.isEnabled = false
                pan.isEnabled = true
                animateBack()
            }
        }
}

对于 SwiftUI,这是我的起始方法

struct DraggableModifier : ViewModifier {
    enum Direction {
        case vertical
        case horizontal
    }

    let direction: Direction

    @State private var draggedOffset: CGSize = .zero

    func body(content: Content) -> some View {
        content
        .offset(
            CGSize(width: direction == .vertical ? 0 : draggedOffset.width,height: direction == .horizontal ? 0 : draggedOffset.height)
        )
        .gesture(
            DragGesture()
            .onChanged { value in
                self.draggedOffset = value.translation
            }
            .onEnded { value in
                self.draggedOffset = .zero
            }
        )
    }
}

使用 SwiftUI 方法,我可以毫无问题地垂直拖动我的视图。我已经研究了 DragGesture,但我不是 100% 的最佳起点。

非常感谢任何建议。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)