【问题标题】:How i can use CGAffineTransform for correct drag and drop我如何使用 CGAffineTransform 进行正确的拖放
【发布时间】:2019-02-07 22:27:44
【问题描述】:

我想通过 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:
        ()
    }
}

【问题讨论】:

    标签: swift animation uipangesturerecognizer


    【解决方案1】:

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

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

    【讨论】:

    • 有了这条线,稍微拖拽一下textView离开屏幕
    • 尝试去掉 case .ended 语句?
    • 我不能这样做,因为当用户停止拖动时,我会启动动画以使 textView 在屏幕上按当前 Y 位置居中。
    【解决方案2】:

    解决了一个问题

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

    【讨论】:

      猜你喜欢
      • 2020-03-09
      • 2010-11-22
      • 1970-01-01
      • 2019-10-13
      • 2014-03-28
      • 2020-08-06
      • 2015-05-03
      • 2012-02-12
      • 1970-01-01
      相关资源
      最近更新 更多