Search code examples
swiftuitextfieldmkannotation

Use a text field to set the title of an MKAnnotation in Swift


having registered a long press at a point on the map, I'd like a text field to pop up, so I can set the input as the title of a pin dropped at that point. How would I go about doing this? Heres my code which currently registers a longpress and drops a pin, that all works fine! I'm not sure how to bring up a text field and get the users input though

func DropPin(gestureRecognizer:UIGestureRecognizer) {
     if gestureRecognizer.state == .Began {

        var point:CGPoint = gestureRecognizer.locationInView(self.Map)

        var pinLoc: CLLocationCoordinate2D = self.Map.convertPoint(point, toCoordinateFromView: self.Map)



        let x = CustomAnnotation(coordinate: pinLoc, title: "Pin", subtitle: "Pin", imageName: "TouchPin")
        self.Map.addAnnotation(x)
    }
}

Solution

  • There are several ways to do so, but you can choose one of the two for example.

    In your view, you add a text field where the user set the title before you drop the pin. But that might not be intuitive or look bad (if you need to have a full screen map for example).

    So, what I would suggest is to fire an UIAlertController with a text field inside. Here is an example of how you could do it. Either you :

    1. Create the annotation
    2. Add it to the map
    3. An alert appear
    4. The user enter a name (keep it somewhere)
    5. You retrieve the last annotation you've added
    6. You set it's title with the name entered previously

    Or :

    1. You detect your long press
    2. An alert appear
    3. The user enter a name (keep it somewhere)
    4. Create your annotation with the name entered previously
    5. Add it to the map

    Those are just 2-3 examples. You might think of something else :)