swift4

(Swift4コードで書く)SubViewを追加してPan(Drag)で動かす

pan.gif

コード

ViewController.swift
import UIKit

class ViewController: UIViewController {
    var label:UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        //SubViewを作成
        let pos:CGRect = CGRect.init(x: 0, y: 0, width: 250, height: 250)
        let SubView   = UIView.init(frame: pos)
        let bgColor    = UIColor.blue
        SubView.backgroundColor = bgColor

        //Panの処理を追加し、SubViewにpanを登録
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.panView(sender:)))
        SubView.addGestureRecognizer(panGesture)

        //座標表示用のラベルを作成しSubViewに追加
        let bWidth  : CGFloat = 200
        let bHeight : CGFloat = 50
        let posX    : CGFloat = SubView.bounds.width/2 - bWidth/2
        let posY    : CGFloat = SubView.bounds.height/2 - bHeight/2

        label                 = UILabel(frame: CGRect(x: posX, y: posY, width: bWidth, height: bHeight))
        label.backgroundColor = UIColor.black
        label.textColor       = UIColor.white

        label.textAlignment   = NSTextAlignment.center

        label.text = "\(pos.minX), \(pos.minY)"

        SubView.addSubview(label)

        //Selfに追加
        self.view.addSubview(SubView)
    }

    //Pan実行時のメソッド
    @objc func panView(sender: UIPanGestureRecognizer) {
        //移動量を取得
        let move:CGPoint = sender.translation(in:self.view)
        //ドラッグした部品の座標に移動量を加算
        sender.view!.center.x += move.x
        sender.view!.center.y += move.y
        //ラベルに現在座標を表示する
        label.text = "\(sender.view!.frame.origin.x), \(sender.view!.frame.origin.y)"
        //移動量を0に
        sender.setTranslation(CGPoint.zero, in: self.view)
    }
}