SwiftUi 画像 をドラッグして自由に動す方法です
完成イメージ
実装コード
.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
で画面中央を取得してます。
中央からどの程度動かすかposition
をDragGesture().onChanged
から取得して表示位置をドラッグに合わせて変更してます。
onEnded
で指を離したら中央に戻ります。
リファレンス