MontanaCoder23 MontanaCoder23 - 5 months ago 22
Swift Question

Triggering push segue from long press on map view

My app is supposed to allow users to view a list of places (as annotations) on a map view and add their own custom places. It uses three view controllers with a navigation controller- a tableview for the list of places, a basic view controller with a mapview for the map, and a basic view controller with a text field for adding a name for their custom pin. Story board:

Story Board view

The problem occurs with the highlighted segue from the map view controller to the Add Label view controller. I have attempted to set up so that when a user long-presses on the map view for more than 1-second, it manually segues to the Add Label view controller, using prepareForSegue send latitude and longitude.

However, when I execute the long press on the simulator, it seems to segue twice. The top screen's navigation button simply says "Back", which leads to a duplicate of the Add Label screen with a nav button leading correctly back to the Map View controller.

Code for long press gesture recognizer from viewDidLoad:

var uilpgr = UILongPressGestureRecognizer(target: self, action: "action:")

uilpgr.minimumPressDuration = 1

map.addGestureRecognizer(uilpgr)


Code for "action" triggered by long press:

func action(gestureRecognizer:UIGestureRecognizer) {

touchPoint = gestureRecognizer.locationInView(self.map)

newCoordinate = map.convertPoint(touchPoint!, toCoordinateFromView: self.map)
//3
self.performSegueWithIdentifier("NamePlace", sender: self)
//4
}


Code preparing for segue (to send coordinates:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "NamePlace" {

let lat = newCoordinate!.latitude
let long = newCoordinate!.longitude

let viewController = segue.destinationViewController as! AddLabelViewController

viewController.latitude = lat
viewController.longitude = long

}
}


I tried setting breakpoints at 3 and 4 in the "action" code (as well as during the prepareForSegue method) and it seemed as though it executed the "action" code twice before triggering the segues, which then happened back to back.

Can anyone explain why this is happening and how to fix it? (I'm also open to suggestions of better ways to accomplish the task of naming custom points dropped). Thanks!

Answer

Try to change your action method like this

 func action(gestureRecognizer:UIGestureRecognizer) {

    if (gestureRecognize.state == .Began) {
        touchPoint = gestureRecognizer.locationInView(self.map)
        newCoordinate = map.convertPoint(touchPoint!, toCoordinateFromView: self.map)
        self.performSegueWithIdentifier("NamePlace", sender: self)
    }
}

Hope this will help you.

Comments