UIViewをパンジェスチャー(ドラッグ)で移動させる

今回はジェスチャーのひとつUIPanGestureRecognizerでUIViewを動かせるViewにしてみます

PCでのドラッグ操作になります

環境:swift5

コード全文

Storyboardは使用していませんのでコードコピペで再現できます

import UIKit

class ViewController: UIViewController {
    
    let panView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.panView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        self.panView.backgroundColor = .red
        self.view.addSubview(self.panView)
        //panViewをパンジェスチャー(ドラッグ)で動かせるように
        let panGesture = UIPanGestureRecognizer()
        panGesture.addTarget(self, action: #selector(panAction(_:)))
        panView.addGestureRecognizer(panGesture)
        
    }
    
    @objc func panAction(_ gesture: UIPanGestureRecognizer) {
        //View移動中にボーダーを表示する
        if gesture.state == .began {
            self.panView.layer.borderColor = UIColor.blue.cgColor
            self.panView.layer.borderWidth = 5
        }else if gesture.state == .ended {
            self.panView.layer.borderColor = UIColor.clear.cgColor
            self.panView.layer.borderWidth = 0
        }

        // Viewをドラッグした量だけ動かす
        let point: CGPoint = gesture.translation(in: self.panView )
        let movedPoint = CGPoint(x:self.panView.center.x + point.x, y:self.panView.center.y + point.y)
        self.panView.center = movedPoint
               
        // ドラッグで移動した距離をリセット
        gesture.setTranslation(CGPoint.zero, in: self.panView)
        
    }
}

移動に関するpanActionをUIViewにつけるだけで後は問題なく動きます