1

这是我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% 的最佳起点。

非常感谢任何建议。

4

0 回答 0