0
我無法理解viewForAnnotation方法的代碼以及何時調用它。我的意圖是根據引腳顏色的顏色顯示特定的標註。在第一次加載mapView時,標註顯示正確,但是在切換視圖控制器後,根據引腳顏色不能正確顯示標註按鈕。我有一個預感,這可能與viewForAnnotation調用時有關(無論每次出現地圖時調用它)。我無法弄清楚什麼是錯誤的,因爲我不確定代碼的每個部分是幹什麼的。Swift 3.0 Map viewForAnnotation不輸出正確標註
func mapView(_ map: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if (annotation is MKUserLocation) {
return nil
}
let identifier = "pinAnnotation"
// In particular I am not sure what the code below does
if let pin = annotation as? ColorPointAnnotation {
if let view = map.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView {
view.annotation = annotation
view.pinTintColor = pin.color ?? .purple
return view
} else {
let view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.isEnabled = true
view.canShowCallout = true
view.pinTintColor = pin.color ?? .purple
let btn = UIButton(type: .detailDisclosure)
view.rightCalloutAccessoryView = btn
if view.pinTintColor == .red || view.pinTintColor == .green {
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
button.setBackgroundImage(UIImage(named: "car"), for: .normal)
button.addTarget(self, action: #selector(MapVC.getDirections), for: .touchUpInside)
view.leftCalloutAccessoryView = button
} else {
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
button.setBackgroundImage(UIImage(named: "other"), for: .normal)
button.addTarget(self, action: #selector(MapVC.other), for: .touchUpInside)
view.leftCalloutAccessoryView = button
}
return view
}
}
if let annotationView = map.dequeueReusableAnnotationView(withIdentifier: identifier) {
annotationView.annotation = annotation
return annotationView
} else {
let annotationView = MKPinAnnotationView(annotation:annotation, reuseIdentifier: identifier)
annotationView.isEnabled = true
annotationView.canShowCallout = true
let btn = UIButton(type: .detailDisclosure)
annotationView.rightCalloutAccessoryView = btn
if annotationView.pinTintColor == .red || annotationView.pinTintColor == .green {
let smallSquare = CGSize(width: 120, height: 120)
let button = UIButton(frame: CGRect(origin: CGPoint(x: 0,y :0), size: smallSquare))
button.setBackgroundImage(UIImage(named: "car"), for: .normal)
button.addTarget(self, action: #selector(MapVC.getDirections), for: .touchUpInside)
annotationView.leftCalloutAccessoryView = button
} else {
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
button.setBackgroundImage(UIImage(named: "other"), for: .normal)
button.addTarget(self, action: #selector(MapVC.other), for: .touchUpInside)
annotationView.leftCalloutAccessoryView = button
}
return annotationView
}
}
爲了澄清,當你說的MapView顯示了重新註解gion,你的意思是如果註釋被放置,或者用戶看到的當前視圖是否有註釋。還有什麼意思,「把任何UIView作爲註釋在地圖上」? – Kevin
@Kevin是的,如果註釋添加在一個區域內的座標,然後顯示使用這種委託方法,如果實施,再次檢查我的答案已更新 –
@Kevin您正在使用2種類型的註釋?,我想missunderstood您的問題 –