2012-10-12 31 views
6

tôi thêm chú thích vào bản đồ của tôi theo cách này:Thay đổi pin màu MKMapView

MyAnnotation *annotationPoint2 = [[MyAnnotation alloc] init]; 
annotationPoint2.coordinate = anyLocation; 
annotationPoint2.title = [NSString stringWithFormat:@"%@", obj]; 
annotationPoint2.subtitle = @""; //or set to nil 
annotationPoint2.keyValue = [NSString stringWithFormat:@"%@", key]; 
[mapPins addAnnotation:annotationPoint2]; 

Các chân đều đỏ, và tôi muốn tất cả chúng màu xanh lá cây. Làm thế nào tôi có thể thay đổi màu sắc? Tôi đã thử những điều sau đây, nhưng nó vẫn mang lại một dấu đỏ:

annotationPoint2.pinColor = MKPinAnnotationColorGreen; 

Trả lời

18
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation 
    { 
    MKPinAnnotationView *annView=[[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"pin"]; 
    annView.pinColor = MKPinAnnotationColorGreen; 
    return annView; 
    } 
+0

mã này hoạt động, nhưng ngay cả vị trí người sử dụng hiện tại trở nên xanh, ngay cả khi tôi muốn nó màu xanh với các vòng tròn quanh nó. Làm thế nào tôi có thể làm điều đó? – Alessandro

+4

nếu ([[chú thích tiêu đề] isEqualToString: @ "Vị trí hiện tại"]) { annView.pinColor = MKPinAnnotationColorGreen; } else {annView.pinColor = MKPinAnnotationColorRed;} – casillas

+0

@Alessandro Bạn cần trả về nil khi chú thích == mapView.userLocation để hiển thị chấm màu xanh cho vị trí của người dùng và vòng tròn xung quanh nó – amitshinik

5

Thuộc tính pinColor được định nghĩa trong lớp MKPinAnnotationView (không phải là giao thức MKAnnotation).

Bạn tạo một MKPinAnnotationView trong phương thức ủy quyền viewForAnnotation. Nếu bạn chưa triển khai đại biểu đó, bạn sẽ nhận được các ghim màu đỏ chuẩn theo mặc định.

Trong phương thức ủy nhiệm đó, bạn tạo một phiên bản MKPinAnnotationView và bạn có thể đặt pinColor thành màu xanh lá cây.

1

Swift3 là theo cách này:

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

    let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin") 

    if annotation.title! == "My Place" { 

     annotationView.pinTintColor = UIColor.green 

    } else { 

     annotationView.pinTintColor = UIColor.red 
    } 


    return annotationView 
}