我正在爲iOS開發應用程序,並在我的地圖視圖中遇到自定義註釋問題。添加/刪除註釋時奇怪的自定義註釋行爲
這裏的理念是:
1)我在用戶位置加載到地圖,從這個位置我發送到我的後端服務器的請求來檢索所有感興趣的景點。
2)我有一個自定義註解如下:
class CustomPointAnnotation: MKPointAnnotation {
var imageName: String?
var activeImageName : String?
var trainCrossingId : Int?
var notificationCount : UILabel = UILabel()
var labelIsHidden : Bool = true
}
當我添加註釋到地圖,我動態設置notificationCount
標籤使用,我已經從我的火力地堡數據庫中檢索數據。
3)用戶能夠增加/減少他們當前位置周圍半徑的大小。選擇此新半徑後,我使用mapView.removeAnnotations(mapView.annotations)
刪除所有註釋,然後使用選定半徑從服務器檢索的新數據重新添加這些註釋。
的問題:
當最初加載視圖,註釋是否按預期工作與正確的標籤設置等
然而,一旦用戶更新半徑和我刪除/添加以前的註釋,註釋及其相應的標籤未按預期顯示。
例如,這是地圖的外觀時,首先進入的觀點,如:
預期的數據是初始圖像中顯示的內容(當首次進入視圖時),但是當半徑更新時,我的註釋的z值不受尊重,並且notificationCount
不正確(例如,第二個圖中找到的第三個點應該沒有標籤)。這很奇怪,因爲我已經設置了打印語句和斷點來監視func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {...}
中的每個註釋,並且這些值是正確的和我期望的,但是該視圖不顯示這些值。
任何有關可能會出錯的想法?提前致謝!
編輯包括以下MapView的委託:
// Custom annotation view
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if !(annotation is CustomPointAnnotation) {
return nil
}
let reuseId = "trainPin"
var anView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
}
else {
anView?.annotation = annotation
}
let cpa = annotation as! CustomPointAnnotation
let icon : UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
icon.image = UIImage(named:cpa.imageName)
icon.layer.zPosition = 1
anView?.rightCalloutAccessoryView = cpa.annotationButton
anView?.addSubview(cpa.notificationCount)
anView?.addSubview(icon)
anView?.frame = CGRect(x: 0, y:0, width:32, height:32)
anView?.canShowCallout = true
return anView
}
您可以發佈您的'FUNC MapView類(_ MapView類:的MKMapView,viewFor註釋:MKAnnotation)代碼 - > MKAnnotationView'? – chengsam
當然,我剛編輯過將它添加到原始問題中。謝謝@chengsam – Dayna