LoginSignup
19

More than 5 years have passed since last update.

UIPanGestureRecognizerでDragする。

Posted at

iOSアプリでドラッグ&ドロップしてみる件についてをSwiftでやってみました。

環境

  • iOS: 8.4.1
  • Xcode6
  • ProjectTemplate: Single View Application

Objectの用意

ドラッグするためのオブジェクトを用意します。今回はViewを置きました。右のピンクのViewで説明します!
a.png

ドラッグの実装

まず、右下のオブジェクトがたくさんあるところから、Pan Gesture RecognizerをドラッグしたいViewにドラッグアンドドロップします。
そしたら、このタッチイベントの宣言とアクション紐付けします。
Main.storyboardでViewController.swiftと2画面開いて、OutletとActionで紐付けします。
typeをUIPanGestureRecognizerにしてnameはpanGestureにしてあります。

ViewController.swift

    @IBOutlet var panGesture: UIPanGestureRecognizer! //紐付けすると出てきます。

    @IBAction func dragGesture(sender: UIPanGestureRecognizer) { //こちらも紐付けによって

        var point: CGPoint = sender.translationInView(self.view)
        var movedPoint: CGPoint = CGPointMake(sender.view!.center.x + point.x,
        sender.view!.center.y + point.y)
        sender.view!.center = movedPoint
        sender.setTranslation(CGPointZero, inView: self.view)
    }

初めの方の紐付けがちゃんとできてれば動く!

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19