2016-11-08 82 views
0

我很新来swift(来自python)我正在努力创建一个MKAnnotationView。我遵循了ray wenderlich的教程,但代码似乎已过时。函数调用似乎不起作用或产生意图在引脚注释中的“i”。这里是我目前使用的代码:MKAnnotationView Swift添加“信息”按钮

import MapKit 

extension ViewController: MKMapViewDelegate { 

// 1 
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { 
    if let annotation = annotation as? Artwork { 
     let identifier = "pin" 
     var view: MKPinAnnotationView 
     if let dequeuedView = MapView.dequeueReusableAnnotationView(withIdentifier: identifier) 
      as? MKPinAnnotationView { // 2 
      dequeuedView.annotation = annotation 
      view = dequeuedView 
     } else { 
      // 3 
      view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) 
      view.canShowCallout = true 
      view.calloutOffset = CGPoint(x: -5, y: 5) 
      let button = UIButton(type:.detailDisclosure) 
      view.rightCalloutAccessoryView = button as UIView 
     } 
     return view 
    } 
    return nil 
    } 
} 

我正在运行Xcode 8.1,任何帮助将不胜感激。

回答

2

我正在使用Xcode 8.1和Swift 3.0。出于某种原因,委托方法不是射击,直到你在故事板设置委托:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? 
    { 
     if annotation is MKUserLocation {return nil} 

     let reuseId = "pin" 

     var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView 
     if pinView == nil { 
      pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) 
      pinView!.canShowCallout = true 
      pinView!.animatesDrop = true 
      let calloutButton = UIButton(type: .DetailDisclosure) 
      pinView!.rightCalloutAccessoryView = calloutButton 
      pinView!.sizeToFit() 
     } 
     else { 
      pinView!.annotation = annotation 
     } 


     return pinView 
    } 

的按钮动作

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { 
     if control == view.rightCalloutAccessoryView { 
      print("button tapped") 
     } 
    } 

我附上示例项目您的问题

Map Sample Project Swift 3. 0 Xcode 8.1

+0

我m得到以下错误:从我的ViewController中有MapView.delegate = self它失败,因为_cannot分配值键入'视图控制器'吨ype'MKMapView Delegate?'_ –

+0

这是一个示例。和Swift 3代码。将其更改为您需求的Swift较低版本 – Vinodh

+0

我相信我正在运行swift 3 –