2017-08-23 47 views
0

我有麻煩可以在MapView中選擇自定義註釋。我嘗試幾種方法,都沒有成功:didSelect爲MKAnnotationView沒有射擊

  • 使用MKMapViewDelegate的didSelect
  • 使用的UIButton被添加到AnnotationView
  • 使用UITapGestureRecognizer的ImageView的,它應該用於註釋

你可以找到所有這些方法在下面的代碼註釋:

override func viewDidLoad() { 
    super.viewDidLoad() 
    // some more initialization code 

    for item in items { 
     let annotation = IdentifiedMKPointAnnotation() // has only one additional property named "id" 

     annotation.coordinate = CLLocationCoordinate2D(latitude: item.spots[0].latitude!, longitude: item.spots[0].longitude!) 
     annotation.id = i 

     self.mapView.addAnnotation(annotation) 

     i += 1 
    } 
} 


// MARK: - MapViewDelegate 
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { 
    let item = self.items[(annotation as! IdentifiedMKPointAnnotation).id!] 

    let annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "") 
    //annotationView.canShowCallout = false 
    //annotationView.isEnabled = false 

    let imageView = UIImageView() 
    imageView.frame.size = CGSize(width: 40, height: 40) 
    imageView.layer.cornerRadius = 20 
    imageView.layer.masksToBounds = true 
    imageView.af_setImage(withURL: URL(string: item.images.count > 0 ? item.images[0] : item.image!)!) 
    imageView.contentMode = .scaleAspectFill 

    //let gr = UIGestureRecognizer(target: self, action: #selector(annotationSelected(_:))) 
    //imageView.addGestureRecognizer(gr) 
    //imageView.isUserInteractionEnabled = true 

    //let button = UIButton() 
    //button.frame.size = CGSize(width: 40, height: 40) 
    //button.setImage(#imageLiteral(resourceName: "play_arrow"), for: .normal) 
    //button.addTarget(self, action: #selector(annotationSelected(_:)), for: .touchUpInside) 

    annotationView.addSubview(imageView) 
    //annotationView.addSubview(button) 

    return annotationView 
} 

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { 
    performSegue(withIdentifier: "showDetail", sender: self.items[(view.annotation as! IdentifiedMKPointAnnotation).id!]) 

    view.setSelected(false, animated: false) 
} 

func annotationSelected(_ sender: UIImageView) { 
    performSegue(withIdentifier: "showDetail", sender: self.items[((sender.superview as! MKAnnotationView).annotation as! IdentifiedMKPointAnnotation).id!]) 
} 

任何想法爲什麼這個動作不是/不是正在射擊?

+1

我沒有看到任何地方設置委託在碼。你真的做到了嗎? –

+0

是的,我已經在故事板中做過了。奇怪的是,那「didSelect」的作品,當我點擊圓形imageview –

回答

2

如果註釋的title爲空,則不調用didSelect委託。嘗試下面的代碼。

let annotation = IdentifiedMKPointAnnotation() 
annotation.title = "title" 
+0

以外的一點點我已經嘗試設置標題 - 仍然無法正常工作。 –