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

时间:2019-02-07 22:27:44

标签: swift animation uipangesturerecognizer

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

第一次拖动

enter image description here

第二次拖动

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

2 个答案:

答案 0 :(得分:0)

CGAffine转换对于您的任务不是必需的。试试:

情况已更改: textview.center = CGPoint(x:textview.x + translation.x,                 y:textview.y + translation.y)

答案 1 :(得分:0)

解决了一个问题

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