記事一覧
Swift MkMapViewで地図アプリ作成してみた(記事一覧)
UILongPressGestureRecognizerでロングタップを検出する
- 
storyboardにUILongPressGestureRecognizerを貼り付ける。 「command + shift + l(エル)」でObjects Libraryを表示する。 
 Long Press Gesture Recognizerをstoryboard上のデバイスまでドラックしてドロップする。
  
- 
ViewController.swiftにUILongPressGestureRecognizerの変数を定義する。 ViewController.swift:UILongPressGestureRecognizerの変数を定義class ViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet var mapView: MKMapView! var locManager: CLLocationManager! @IBOutlet var longPressGesRec: UILongPressGestureRecognizer!
- 
UILongPressGestureRecognizer変数にUI Objectを紐付ける。 Long Press Gesture Recognizerで右クリックし、Referencing Outletsの○をView Controllerまでドラックしてドロップする。 
  
- 
UILongPressGestureRecognizerのdelegateを登録する UIGestureRecognizerDelegateを継承する。 ViewController.swift:UIGestureRecognizerDelegateを継承するclass ViewController: UIViewController, CLLocationManagerDelegate, UIGestureRecognizerDelegate {ロングタップした時にCallされる関数を実装する。 
 関数名は任意で良いが、引数はUILongPressGestureRecognizerを指定する。ViewController.swift:ロングタップを検出する// UILongPressGestureRecognizerのdelegate:ロングタップを検出する @IBAction func mapViewDidLongPress(_ sender: UILongPressGestureRecognizer) { // ロングタップ開始 if sender.state == .began { } // ロングタップ終了(手を離した) else if sender.state == .ended { }定義した関数に、UI ObjectのSent Actionsを紐付ける。   
タップした位置の緯度経度を取得する
- 
タップした位置(CGPoint)を指定してMkMapView上の緯度経度を取得する ViewController.swift:タップした位置(CGPoint)を指定してMkMapView上の緯度経度を取得する// UILongPressGestureRecognizerのdelegate:ロングタップを検出する @IBAction func mapViewDidLongPress(_ sender: UILongPressGestureRecognizer) { // ロングタップ開始 if sender.state == .began { } // ロングタップ終了(手を離した) else if sender.state == .ended { // タップした位置(CGPoint)を指定してMkMapView上の緯度経度を取得する let tapPoint = sender.location(in: view) let center = mapView.convert(tapPoint, toCoordinateFrom: mapView) let lonStr = center.longitude.description let latStr = center.latitude.description print("lon : " + lonStr) print("lat : " + latStr) }



