[SwiftUI] DragGesture 画像をドラッグする

GestureにはViewをタップするだけでなくドラッグも認識してくれ、画像のドラッグも簡単にできます。

Xcode 13.4.1

DragGesture

画像をドラッグさせるのはUIKitではtouchEventなどを使っていました

画像を指でドラッグさせるなどは、スマホになってできるようになった画期的な機能ですがどのようにプログラムするのでしょうか?意外と簡単です、簡単…

 

SwiftUIではDragGestureを使うことで可能となります。

Previewで画像をドラッグさせてみましょう。

 

DragGesture.Value

ViewのDragGestureを認識するために、Modifierから gesture(_:include:) を追加します。

Textの「Hello world!」を「Command」を押しながら選択

「Show SwiftUI Inspector…」からダイアログ下の「Add Modifier」に検索文字を入力してgestureを追加します

 

gesture は他のタップやロングプレスなども扱えますが
ここではDragGesture()を使います

 

DragGestureのイニシャライズ:

  • minimumDistance:ドラッグを認識する範囲
  • coordinateSpace:
    • local:Viewの座標系
    • grobal:画面の座標系

onChanged:

Gestureが変化したときに実行するアクションを追加

 

onEnded:Gestureが終わった時のアクションを追加

 

updating: Gestureが変化したときにgesture state propertyをアップデートする、ただし値は保持されない


DragGesture.Value プロパティとして以下のものがあります

  • var location: CGPoint
    • 現在の場所
  • var predictedEndLocation: CGPoint
    • 現在の速度からの今止まった場合の最終位置の予測
  • var predictedEndTranslation: CGSize
    • 現在の速度からの今止まった場合の最終移動の予測
  • var startLocation: CGPoint
    • gestureの開始位置
  • var time: Date
    • 現在のドラッグイベントに関連付けられた時間
  • var translation: CGSize
    • ドラッグの開始から現在までの総移動合計
DragGesture.Value のインスタンスを生成して、ドラッグの変化に応じてViewの座標を変えていくとドラッグが実現します。

サンプルコード

適当な画像を1枚用意して(ここでは handbag@2x.png)
Assets.xcassetsに入れます。

 

画像のposition.x, position.yを初期化

onChanged と onEnded を使いクロージャーで
x, y の移動量の変化を画像の位置として設定します。

ContentView.swift

 

画像がドラッグされます。

References:
Gestures | Apple Developer Documentation
DragGesture — SwiftUI | Apple Developer Documentation
DragGesture.Value — DragGesture | Apple Developer
CoordinateSpace — SwiftUI | Apple Developer Documentation
updating(_:body:) — DragGesture | Apple Developer
onEnded(_:) — Gesture | Apple Developer Documentation
onChanged(_:) — DragGesture | Apple Developer Documentation