H.N. H.N. - 1 year ago 121
Swift Question

LongPress in MapKit

I am bulding an app in Swift 3.

Everything seams to be working ok however when I longPress in the map it acts like if it was longpressed twice.
I don't know why...
i've made a print inside the longpress, to count the longpresses and every time I longpress (one time) it detects two long presses... why is this happening? Whats wrong with it?

import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate {

@IBOutlet var map: MKMapView!

var numberOfLongPress : Int = 0

override func viewDidLoad() {

let latitude: CLLocationDegrees = 38.925560

let longitude: CLLocationDegrees = -9.229723

let lanDelta: CLLocationDegrees = 0.05

let lonDelta: CLLocationDegrees = 0.05

let span = MKCoordinateSpan(latitudeDelta: lanDelta, longitudeDelta: lonDelta)

let coordinates = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)

let region = MKCoordinateRegion(center: coordinates, span: span)

map.setRegion(region, animated: true)

let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longpress(gestureRecognizer:)))

lpgr.minimumPressDuration = 0.5



func longpress(gestureRecognizer: UIGestureRecognizer) {

let touchPoint = gestureRecognizer.location(in: self.map)

let coordinate = map.convert(touchPoint, toCoordinateFrom: self.map)

let annotation = MKPointAnnotation()

annotation.coordinate = coordinate

annotation.title = "My Place"


print("longpress activated")

numberOfLongPress = numberOfLongPress + 1

print(numberOfLongPress) //detect number of long presses



Answer Source

Selector is called on every state change, so you better check the state and do what you need to do on .began or .ended.

func longpress(gestureRecognizer: UIGestureRecognizer) {
    guard gestureRecognizer.state == .began else { return }

    // add annotation
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download