MapView設(shè)置自定義大頭針視圖(Obj-C)

子類(MKPinAnnotationView) 默認(rèn)視圖就是大頭針樣式(棒棒糖)
如果要自定義圖像,需要使用父類,不能使用MKPinAnnotationView

演示代碼:

/**
 *  當(dāng)設(shè)置大頭針視圖的時(shí)候大頭針模型時(shí)調(diào)用
 *
 *  @param mapView    地圖視圖
 *  @param annotation 大頭針模型
 *
 *  @return 大頭針視圖
 */
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    
    static NSString *identifier = @"annotation";
    
    // 排除定位大頭針(否則定位大頭針樣式也會(huì)被修改掉)
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }
    
    // 設(shè)置顏色需要使用MKAnnotationView的子類才行  MKPinAnnotationView
    MKAnnotationView *anno = [mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
    
    if (anno == nil) {
        anno = [[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:identifier];
    }
    // 設(shè)置屬性 (父類(MKAnnotationView)沒有動(dòng)畫滑落和pinTintColor屬性)
    
    // 設(shè)置顯示標(biāo)注
    anno.canShowCallout = YES;

    /*
        MKPinAnnotationView 默認(rèn)視圖就是大頭針樣式(棒棒糖)
        如果要自定義圖像,需要使用父類,不能使用MKPinAnnotationView
     */
    anno.image = [UIImage imageNamed:@"自拍照"];

    
    return anno;
    
}
annotation.png

這樣設(shè)置后,不會(huì)有動(dòng)畫滑落效果,設(shè)置動(dòng)畫滑落效果,需要在另外一個(gè)代理方法中設(shè)置

演示代碼:

/**
 *  已經(jīng)添加大頭針視圖后調(diào)用(還沒顯示時(shí))
 *
 *  @param mapView 地圖視圖
 *  @param views   所有添加的大頭針視圖
 */
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray<MKAnnotationView *> *)views{
    
    // 遍歷每一個(gè)大頭針視圖
    for (MKAnnotationView *anno in views) {
        
        // 排除定位大頭針(否則定位大頭針樣式也會(huì)被修改掉)
        if ([anno isKindOfClass:[MKUserLocation class]]) {
            return ;
        }
        
        // 記錄目標(biāo)位置
        CGRect targetAnno = anno.frame;
        
        // 改大頭針視圖Y坐標(biāo)(模擬動(dòng)態(tài)滑落)
        anno.frame = CGRectMake(targetAnno.origin.x,0,targetAnno.size.width,targetAnno.size.height);
        
        // 動(dòng)畫移動(dòng)位置到目標(biāo)位置
        [UIView animateWithDuration:0.5 animations:^{
           
            anno.frame = targetAnno;
            
        }];
        
    }
    
    
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容