2017-01-27 2 views
1

Может ли кто-нибудь помочь мне добавить другое действие кнопки во вторую аннотацию/вывод (аннотация2), Теперь кнопка выполняет ту же работу в двух аннотации указывают, как выполнять другую работу друг с другом. Я использую Swift3 в своем проекте, и это мой код. спасибоКак добавить другое действие кнопки во вторую аннотацию/вывод в виде карты с помощью swift2

Это мой код.

import UIKit 
    import MapKit 
    import CoreLocation 

class MyAnnotation: MKPointAnnotation { 
     var uniqueId: Int! 
} 

    class LocationViewController: UIViewController , MKMapViewDelegate , CLLocationManagerDelegate{ 

    @IBOutlet weak var map: MKMapView!{ 

    didSet{ 
     map.delegate = self 
    } 
} 

@IBOutlet weak var locationInfo: UITextView! 


override func viewDidLoad() { 
    super.viewDidLoad() 


    let locations = CLLocationCoordinate2DMake(33.314627, 44.303500) 

    let location2 = CLLocationCoordinate2DMake(33.312149, 44.3024567) 

    let span = MKCoordinateSpanMake(0.02, 0.02) 

    let span2 = MKCoordinateSpanMake(0.02, 0.02) 

    let region = MKCoordinateRegionMake(locations, span) 

    let region2 = MKCoordinateRegionMake(location2, span2) 


    map.setRegion(region, animated: true) 

    map.setRegion(region2, animated: true) 


    let annotation = MyAnnotation() 
    //annotation.setCoordinate(location) 
    annotation.coordinate = locations 
    annotation.title = "Zaid Homes" 
    annotation.subtitle = "Hay aljameaa" 

    annotation.uniqueId = 1 

    map.addAnnotation(annotation) 

    let annotation2 = MyAnnotation() 
    //annotation.setCoordinate(location) 
    annotation2.coordinate = location2 
    annotation2.title = "Zaid " 
    annotation2.subtitle = "aljameaa" 

    annotation.uniqueId = 2 

    map.addAnnotation(annotation2) 

    //Showing the device location on the map 
    self.map.showsUserLocation = true; 

} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { 
    var view = mapView.dequeueReusableAnnotationView(withIdentifier: "AnnotationView Id") 
    if view == nil{ 
     view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "AnnotationView Id") 
     view!.canShowCallout = true 
    } else { 
     view!.annotation = annotation 
    } 

    view?.leftCalloutAccessoryView = nil 
    view?.rightCalloutAccessoryView = UIButton(type: UIButtonType.detailDisclosure) 


    return view 
} 

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { 

    if (control as? UIButton)?.buttonType == UIButtonType.detailDisclosure { 
     mapView.deselectAnnotation(view.annotation, animated: false) 
     if let myAnnotation = view.annotation as? MyAnnotation { 
      if (myAnnotation.uniqueId == 1) { 
       performSegue(withIdentifier: "info", sender: view) 
      } 
      else { 
       performSegue(withIdentifier: "info2", sender: view) 
      } 
     }    
    } 
} 

} 

ответ

1

Самым простым способом узнать, на котором аннотация касания используется создание пользовательского класса аннотаций и добавление его аннотации. Поэтому создайте один класс аннотации MyAnnotation дочернего класса MKPointAnnotation и сохраните один уникальный идентификатор с помощью нескольких аннотаций.

class MyAnnotation: MKPointAnnotation { 
    var uniqueId: Int! 
} 

Теперь вам нужно добавить аннотацию типа MyAnnotation вместо MKPointAnnotation.

let annotation = MyAnnotation() 
annotation.coordinate = locations 
annotation.title = "Zaid Homes" 
annotation.subtitle = "Hay aljameaa" 
//Set uniqueId for annotation 
annotation.uniqueId = 1  
map.addAnnotation(annotation) 

let annotation2 = MyAnnotation() 
annotation2.coordinate = location2 
annotation2.title = "Zaid " 
annotation2.subtitle = "aljameaa" 
//Set uniqueId for annotation 
annotation2.uniqueId = 2  
map.addAnnotation(annotation2) 

Теперь проверьте этот uniqueId в calloutAccessoryControlTapped метод, на котором аннотации вы повернутые.

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { 

    if (control as? UIButton)?.buttonType == UIButtonType.detailDisclosure { 
     mapView.deselectAnnotation(view.annotation, animated: false) 
     if let myAnnotation = view.annotation as? MyAnnotation { 
      if (myAnnotation.uniqueId == 1) { 
       performSegue(withIdentifier: "info1", sender: view) 
      } 
      else { 
       performSegue(withIdentifier: "info2", sender: view) 
      } 
     }    
    } 
} 
+0

спасибо за помощь, но у меня есть ошибка (фатальная ошибка: неожиданно обнаружена нуль при разворачивании необязательного значения) ее if (myAnnotation.uniqueId == 1), когда я нажимаю кнопку аннотации 2. –

+0

Вы забыли установить uniqueId для 1 и 2 проверьте мой ответ, когда вы создаете экземпляр 'MyAnnotation' этой строки' annotation.uniqueId = 1' –

+0

Нет, я делаю это, но все та же ошибка. Можете ли вы еще раз прояснить. –

1

вы можете сделать это путем создания два подкласса MKPointAnnotation, а затем в методе делегата вы можете сделать это:

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { 

if view is subClass1 { 
    // do action for subclass 1 

} 
else if view is subClass2 { 
    // do action for subClass 2 
} 
} 

Пожалуйста, дайте мне знать, если это решить вашу проблему.

Update

вы можете сделать внедрение делегирования более проще, как этот Exemple:

class ClassA:MKPointAnnotation{ 
 
    func doActionWhenCalloutTapped(){ 
 
     //do some action 
 
    } 
 
} 
 

 
class ClassB:ClassA{ 
 
    override func doActionWhenCalloutTapped(){ 
 
     //do some actions for annotation of type B 
 
    } 
 
} 
 

 
class ClassC:ClassA{ 
 
    override func doActionWhenCalloutTapped(){ 
 
     //do some actions for annotation of type C 
 
    } 
 
} 
 

 
func viewDidLoad(){ 
 
    super.viewDidLoad() 
 
    let annotation = ClassB() 
 
    //annotation.setCoordinate(location) 
 
    annotation.coordinate = locations 
 
    annotation.title = "Zaid Homes" 
 
    annotation.subtitle = "Hay aljameaa" 
 
    
 
    map.addAnnotation(annotation) 
 
    
 
    let annotation2 = ClassC 
 
    //annotation.setCoordinate(location) 
 
    annotation2.coordinate = location2 
 
    annotation2.title = "Zaid " 
 
    annotation2.subtitle = "aljameaa" 
 
    
 
    map.addAnnotation(annotation2) 
 
} 
 

 
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { 
 
    
 
    (view.annotation as! ClassA).doActionWhenCalloutTapped() 
 
    
 
}

+0

Можете ли вы рассказать мне, что является содержанием этих двух подклассов. –

+0

thaï может быть просто пустым (без дополнительной функции) для этого примера. но это позволяет вам (может быть, в будущем) иметь некоторые новые функции с различным поведением. –

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