This post is part of my collection: Swift 2 – For Beginners.
In this example we will see how to add an annotation to our map when the user tap and hold.
Before we create annotations you should add a MapView to your application, you can see how to do it here.
To detect when the user tapped and hold on the screen we can use the recognizer: UILongPressGestureRecognizer. The next method adds a long press recognizer to our map.
It has 4 parameters:
- The map where the gesture recognized will be added.
- Target, the class that has the action to be executed.
- Action, the selector of the function that will be executed when the gesture is recognized.
- tapDuration, the time in seconds that the user has to hold the tap before the action is executed, by default 1 second.
static func addOnUserTapAction(mapView mapView: MKMapView, target: AnyObject, action: Selector, tapDuration: Double = 1){ // Adding a colon at the end of the selector we pass the recognizer that triggered the action to the action let longPressRecognizer = UILongPressGestureRecognizer(target: target, action: action) longPressRecognizer.minimumPressDuration = tapDuration // Add gesture recognizer to the map mapView.addGestureRecognizer(longPressRecognizer) }
Now we can use the method in our controller:
override func viewDidLoad() { super.viewDidLoad() ... // Adding a colon at the end of the selector we pass the recognizer that triggered the action to the action MapHelper.addOnUserTapAction(mapView: map, target:self, action: "addAnnotation:") }
The method addAnnotation will be executed when our recognizer is fired, it will add an annotation to our map:
func addAnnotation(gestureRecognizer:UIGestureRecognizer){ print("add annotation") let location = MapHelper.getTappedLocation(mapView: self.map, gestureRecognizer: gestureRecognizer) // Add an annotation let annotation = MKPointAnnotation() annotation.coordinate = location; annotation.title = "You created this annotation!" map.addAnnotation(annotation) }
The last thing that we have to do is to write a method to get the coordinate in the map using the point on the screen where the user tapped:
static func getTappedLocation(mapView mapView: MKMapView, gestureRecognizer: UIGestureRecognizer) -> CLLocationCoordinate2D{ // Get the position on the screen where the user pressed, relative to the mapView let touchPoint = gestureRecognizer.locationInView(mapView) // Get location coordinate in map return mapView.convertPoint(touchPoint, toCoordinateFromView: mapView) }