0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SwiftUi 画像 をドラッグして自由に動す方法

Posted at

SwiftUi 画像 をドラッグして自由に動す方法です

完成イメージ

Videotogif (14).gif

実装コード

.swift
import SwiftUI

struct DraggableImageView: View {
    @State private var position: CGSize = .zero  // 画像の位置を管理する変数
    
    var body: some View {
        Image(systemName: "star.fill")
            .resizable()
            .frame(width: 50, height: 50)
            .position(x: UIScreen.main.bounds.width / 2 + position.width,
                      y: UIScreen.main.bounds.height / 2 + position.height)
            .gesture(
                DragGesture()
                    .onChanged { gesture in
                        position = gesture.translation
                    }
                    .onEnded { _ in
                        position = .zero
                    }
            )
    }
}

gestureを設定するとドラッグを取得することができます。
今回は中央に表示しているのでUIScreen.main.bounds.width / 2 と UIScreen.main.bounds.height / 2 で画面中央を取得してます。
中央からどの程度動かすかpositionDragGesture().onChangedから取得して表示位置をドラッグに合わせて変更してます。
onEndedで指を離したら中央に戻ります。

リファレンス

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?