2015-12-17 4 views
1

Я по-прежнему новичок в быстрой и пытается выяснить, как добавить длинную аннотацию на жесткие галстуки на карте.Проблема с UILongPressGestureRecognizer при добавлении в MKMapView

Однако я продолжал получать эту ошибку:

libc++abi.dylib: terminating with uncaught exception of type NSException

там что-то не так с моей addAnotation FUNC?

Заранее спасибо.

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    manager = CLLocationManager() 
    manager.delegate = self 
    manager.desiredAccuracy = kCLLocationAccuracyBest 
    manager.requestWhenInUseAuthorization() 
    manager.startUpdatingLocation() 

    // action = A selector that identifies the method implemented by the target to handle the gesture recognized by the receiver. The action selector must conform to the signature described in the class overview. NULL is not a valid value. 
    var uilpgr = UILongPressGestureRecognizer(target: self, action: "addAnotation") 
    uilpgr.minimumPressDuration = 2.0 
    map.addGestureRecognizer(uilpgr) 
} 

func addAnotation(gestureRecognizer:UIGestureRecognizer) 
{ 
    if(gestureRecognizer.state == UIGestureRecognizerState.Began) 
    { 
     //locationInView = Returns the point computed as the location in a given view of the gesture represented by the receiver. 
     var touchPoint = gestureRecognizer.locationInView(self.map) 

     //convertPoint = convert a point from map to coordinate 
     var newCoordinate = self.map.convertPoint(touchPoint, toCoordinateFromView: self.map) 

     var annotation = MKPointAnnotation() 

     annotation.coordinate = newCoordinate 
     annotation.title = "New Annotation" 
     self.map.addAnnotation(annotation) 
    } 
} 

Вот полный код для справки:

import UIKit 
import MapKit 

class ViewController: UIViewController, CLLocationManagerDelegate { 

@IBOutlet var map: MKMapView! 

var manager: CLLocationManager! 


override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
    manager = CLLocationManager() 
    manager.delegate = self 
    manager.desiredAccuracy = kCLLocationAccuracyBest 
    manager.requestWhenInUseAuthorization() 
    manager.startUpdatingLocation() 

    // action = A selector that identifies the method implemented by the target to handle the gesture recognized by the receiver. The action selector must conform to the signature described in the class overview. NULL is not a valid value. 
    var uilpgr = UILongPressGestureRecognizer(target: self, action: "addAnotation") 
    uilpgr.minimumPressDuration = 2.0 
    map.addGestureRecognizer(uilpgr) 
} 

func addAnotation(gestureRecognizer:UIGestureRecognizer) 
{ 
    if(gestureRecognizer.state == UIGestureRecognizerState.Began) 
    { 
     //locationInView = Returns the point computed as the location in a given view of the gesture represented by the receiver. 
     var touchPoint = gestureRecognizer.locationInView(self.map) 

     //convertPoint = convert a point from map to coordinate 
     var newCoordinate = self.map.convertPoint(touchPoint, toCoordinateFromView: self.map) 

     var annotation = MKPointAnnotation() 

     annotation.coordinate = newCoordinate 
     annotation.title = "New Annotation" 
     self.map.addAnnotation(annotation) 
    } 
} 



func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    print(locations) 
    var userLocation:CLLocation = locations[0] 
    var latitude = userLocation.coordinate.latitude 
    var longitude = userLocation.coordinate.longitude 
    var coordinate = CLLocationCoordinate2DMake(latitude, longitude) 

    var latDelta:CLLocationDegrees = 0.01 
    var lonDelta:CLLocationDegrees = 0.01 
    var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta) // MKCoordinateSpan = A structure that defines the area spanned by a map region. 

    // Mk CoordinateRegion = A structure that defines which portion of the map to display. 
    var region:MKCoordinateRegion = MKCoordinateRegionMake(coordinate, span) 

    self.map.setRegion(region, animated: true) 
} 



override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 


} 

ответ

1

Вам просто нужно добавить двоеточие после addAnotation:

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

В вашей версии, где вы опустите двоеточие , будет вызван метод с этой сигнатурой. Обратите внимание, нет никаких параметров

func addAnotation() 

Так что ваш UILongPressGestureRecognizer пытается вызов выше метода, который является неопределенным, и что является причиной вашего приложения бросить исключение

+0

Привет Джеймс, Спасибо за вашу помощь. –

+0

Могу я узнать, что происходит, если я не поместил двоеточие? Без двоеточия «addAnnotation» не будет вызываться? –

+0

Ввод двоеточия указывает системе на поиск метода, который принимает параметры. Без двоеточия он ищет метод, который не принимает никаких параметров. Что касается системы, то это два разных метода: они могут иметь совершенно разные имена. – farhadf

Смежные вопросы