Pan Gesture-1の使用


  • ViewController.swift
  • //
    //  ViewController.swift
    //  panGesture
    //
    //  Created by yoon-yeoungjin on 2022/03/26.
    //
    
    import UIKit
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            let myView = DraggbleView()
            myView.center = self.view.center
            myView.bounds = CGRect(x: 0, y: 0, width: 100, height: 100)
            myView.backgroundColor = .red
            self.view.addSubview(myView)
            // Do any additional setup after loading the view.
        }
    
    
    }
    
    
  • DraggbleView.swift
  • //
    //  DraggbleView.swift
    //  panGesture
    //
    //  Created by yoon-yeoungjin on 2022/03/26.
    //
    
    import Foundation
    import UIKit
    
    class DraggbleView: UIView {
        override init(frame: CGRect) {
            super.init(frame: CGRect.zero)
            let pan = UIPanGestureRecognizer(target: self, action: #selector(dragging))
            self.addGestureRecognizer(pan)
        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        @objc func dragging(pan: UIPanGestureRecognizer){
            switch pan.state {
            case .began:
                print("began pan gesture")
            case .changed:
                let delta = pan.translation(in: self.superview)
                var myPosition = self.center
                myPosition.x += delta.x
                myPosition.y += delta.y
                print("x : ", myPosition.x, " y: ", myPosition.y)
    
                self.center = myPosition
    
                pan.setTranslation(CGPoint.zero, in: self.superview)
            case .ended:
                print("end pan gesture")
            @unknown default:
                print("err")
            }
        }
    }
    
  • ワークスクリーン