Search code examples
swiftanimationuipangesturerecognizer

How i can use CGAffineTransform for correct drag and drop


I want to do drag and drop for UITextView via UIPanGestureRecognizer with auto aligning on center of the screen. For the first drag it works good, but if i try to do it again my drag start with init point of the UITextView. I don't know how to fix it.

First Drag

enter image description here

Second Drag

enter image description here

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

Solution

  • Solved a problem

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