我如何使用 CGAffineTransform 进行正确的拖放

How i can use CGAffineTransform for correct drag and drop

我想通过 UIPanGestureRecognizer 拖放 UITextView 并在屏幕中心自动对齐。对于第一次拖动效果很好,但如果我再次尝试进行拖动,我的拖动将从 UITextView 的初始点开始。我不知道如何解决它。

第一次拖动

第二次拖动

@objc func handlePan(gesture: UIPanGestureRecognizer) {
    let translation = gesture.translation(in: nil)

    switch gesture.state {
    case .changed:
        dragingText.transform = CGAffineTransform(translationX: translation.x, y: translation.y)

    case .ended:

        UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {

            self.dragingText.transform = CGAffineTransform(translationX: 0, y: translation.y)

        }, completion: nil)
    default:
        ()
    }
}

您的任务不需要 CGAffine 变换。尝试:

案例 .changed: textview.center = CGPoint(x: textview.x + translation.x, y: textview.y + translation.y )

解决了一个问题

 @objc func handlePan(gesture: UIPanGestureRecognizer) {
    let translation = gesture.translation(in: nil)

    switch gesture.state {
    case .changed:

        dragingText.center = CGPoint(x: dragingText.center.x + translation.x, y: dragingText.center.y + translation.y )
        gesture.setTranslation(CGPoint.zero, in: nil)

    case .ended:

        let isInside = isInsideDragableAres()

        if isInside.0 {
            UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.7, options: .curveEaseOut, animations: {
                self.dragingText.center = CGPoint(x: self.view.center.x, y: self.dragingText.center.y + translation.y )
            }, completion: nil)
        }
        else{
            UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.7, options: .curveEaseOut, animations: {
                self.dragingText.center = CGPoint(x: self.view.center.x, y: isInside.1! )
            }, completion: nil)
        }

    default:
        ()
    }
}