LoginSignup
2
1

【SwiftUI】タップした座標を取得する

Posted at

はじめに

onTapGesturecoordinateSpaceという引数が指定できるようになってました。
タップした位置の座標を取得できるようです

実装

import SwiftUI

struct ContentView: View {
    @State private var location: CGPoint? = nil
    
    var body: some View {
        VStack {
            Text(location.map { "\($0.x), \($0.y)" } ?? "No location")
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .onTapGesture(coordinateSpace: .local
        ) { location in
            self.location = location
        }
    }
}

タップした位置の座標を取得することができました
Simulator Screenshot - iPhone 14 - 2023-06-04 at 22.02.24.png

おわり

これを使えば簡単なゲームは作れそうです

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