У меня есть аннотация, которая будет отображаться при длинном нажатии (1 сек), и я хочу создать несколько аннотаций, потому что теперь я могу создать только одну аннотацию. Поэтому я хочу спросить вас, ребята, как я могу это сделать?Больше одного примечания к контакту
Код для установки аннотаций:
in viewDidLoad
var longPress = UILongPressGestureRecognizer(target: self, action: "addAnnotation:")
longPress.minimumPressDuration = 1.0
Mapa.addGestureRecognizer(longPress)
я использовал это:
func mapView(mapView: MKMapView!, didAddAnnotationViews views: [AnyObject]!) {
if let tlacidlo = mapView.viewForAnnotation(mapView.userLocation) {
tlacidlo.rightCalloutAccessoryView = UIButton.buttonWithType(.DetailDisclosure) as! UIButton
}
}
func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
if control == view.rightCalloutAccessoryView {
self.performSegueWithIdentifier("segue", sender: self)
} else {
if let annotation = view.annotation as? MKPointAnnotation {
self.Mapa.removeAnnotation(annotation)
}
}
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if annotation is MKUserLocation {
//return nil
return nil
}
let reuseId = "pin"
var pinView = Mapa.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
if pinView == nil {
//println("Pinview was nil")
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
pinView!.animatesDrop = true
let deleteButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
deleteButton.frame.size.width = 44
deleteButton.frame.size.height = 45
deleteButton.backgroundColor = UIColor.redColor()
deleteButton.setImage(UIImage(named: "trash"), forState: .Normal)
pinView!.leftCalloutAccessoryView = deleteButton
}
var button = UIButton.buttonWithType(UIButtonType.DetailDisclosure) as! UIButton
pinView?.rightCalloutAccessoryView = button
return pinView
}
func addAnnotation(gesture: UIGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.Began {
var touch = gesture.locationInView(self.Mapa)
var coordinate = Mapa.convertPoint(touch, toCoordinateFromView: self.Mapa)
var location = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude)
var loc = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
CLGeocoder().reverseGeocodeLocation(loc, completionHandler: { (placemarks, error) -> Void in
if error == nil {
let placemark = CLPlacemark(placemark: placemarks[0] as! CLPlacemark)
self.cislo = placemark.subThoroughfare != nil ? placemark.subThoroughfare : ""
self.adresa = placemark.thoroughfare != nil ? placemark.thoroughfare : ""
self.mesto = placemark.subAdministrativeArea != nil ? placemark.subAdministrativeArea : ""
self.krajina = placemark.administrativeArea != nil ? placemark.administrativeArea : ""
self.annotation.coordinate = location
self.annotation.title = self.adresa! + " " + self.cislo!
self.Mapa.addAnnotation(self.annotation)
println("Špendlík pridaný!")
}
})
}
}
Вы можете поместить добавочную часть в цикл, но как насчет координаты всех аннотаций? – Amit89
Пожалуйста, обновите свой вопрос и покажите, что означает 'self.annotion' – zisoft
Каждая аннотация должна быть отдельным экземпляром. 'self.annotation' - это единственный экземпляр. 'addAnnotation' игнорирует вызовы для добавления объектов, которые уже были добавлены, поэтому ваш код просто меняет координату и заголовок первой (и только) добавленной аннотации. См. Http://stackoverflow.com/questions/30215109/why-wont-mkpointannotation-show-up-on-map. Для петли здесь не имеет значения. 'self.annotation' не должна быть переменной экземпляра. Сделайте его локальной переменной внутри обработчика завершения обратногоGeocodeLocation и создайте экземпляр там. – Anna