簡體   English   中英

如何在地圖注釋上自動顯示標題/副標題(圖釘)

[英]How to Automatically Display Title/Subtitle on Map Annotation (pin)

我正在將注釋加載到我的地圖視圖上。 加載地圖時,注釋顯示為圖釘。

但是,標題和副標題不會自動出現在圖釘上。 目前,用戶需要在標題顯示之前點擊圖釘。

有沒有辦法在加載地圖時讓標題自動顯示在圖釘上?

(這個問題幾乎是同一件事,但並不完全相同: 在 iphone 中的地圖中顯示當前位置的標題,因為我已經在我的對象中定義了 -title 和 -subtitle 屬性。)

謝謝

要調用的方法是來自 MKMapView 的“selectAnnotation:animated”。

- (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views
{    
    MKAnnotationView *annotationView = [views objectAtIndex:0];
    id<MKAnnotation> mp = [annotationView annotation];
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([mp coordinate] ,350,350);

    [mv setRegion:region animated:YES];    

    [mapView selectAnnotation:mp animated:YES];

}

如果您正在執行調用 setRegion 方法的相同操作,請確保您調用

[mapView selectAnnotation:mp animated:YES];

之后

[mv setRegion:region animated:YES];    

從 iOS 11 開始,有一種新的MKAnnotationView類型叫做MKMarkerAnnotationView ,它可以顯示標題和副標題而不被選中。 檢查https://developer.apple.com/documentation/mapkit/mkmarkerannotationview

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    guard !(annotation is MKUserLocation) else {
        return nil
    }

    if #available(iOS 11.0, *) {
        let annoView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: "HunterAnno")
        annoView.canShowCallout = true
        return annoView
    }

    let annoView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "HunterAnnoLow")
    annoView.canShowCallout = true
    return annoView
}

添加后續答案(適用於 Xcode 11.4 和 Swift 5),因為我遇到了這個確切的問題,但上述答案不起作用。 @zsani 是正確的,因為您需要使用MKMarkerAnnotationView (而不是MKPinAnnotationView )來獲得兩者,但您還必須設置titleVisibilitysubtitleVisibility屬性(盡管titleVisibility似乎默認為MKMarkerAnnotationView )。

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    // do not alter user location marker
    guard !annotation.isKind(of: MKUserLocation.self) else { return nil }

    // get existing marker
    var view = mapView.dequeueReusableAnnotationView(withIdentifier: "reuseIdentifier") as? MKMarkerAnnotationView

    // is this a new marker (i.e. nil)?
    if view == nil {
        view = MKMarkerAnnotationView(annotation: nil, reuseIdentifier: "reuseIdentifier")
    }

    // set subtitle to show without being selected
    view?.subtitleVisibility = .visible

    // just for fun, show green markers where subtitles exist; red otherwise
    if let _ = annotation.subtitle! {
        view?.markerTintColor = UIColor.green
    } else {
        view?.markerTintColor = UIColor.red
    }

    return view
}

共享以防萬一其他人有同樣的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM