@cs2021 cs2021 / ContentView.swift
Created at Thu Jul 22 10:43:01 JST 2021
ドラッグ操作の例
ContentView.swift
Raw
//
//  ContentView.swift
//  DragSample
//
//  Created by takane on 2021/07/22.
//

import SwiftUI

struct ContentView: View {
  @State var position: CGSize = CGSize(width: 200, height: 200)
   
  var body: some View {
    VStack {
      Image("omikuji")
        .resizable()
        .scaledToFit()
        .frame(width: 100, height: 100, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
        .position(x: position.width, y: position.height)
        .gesture(
          DragGesture().onChanged { value in
            self.position = CGSize(
              width: value.startLocation.x + value.translation.width,
              height: value.startLocation.y + value.translation.height
            )
          }
          .onEnded { value in
            self.position = CGSize(
              width: value.startLocation.x + value.translation.width,
              height: value.startLocation.y + value.translation.height
            )
          }
      )
      Spacer()
      Text("x:\(position.width), y:\(position.height)")
    }
  }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}