2017-05-17 4 views
0

지도 주석의 핀 색상을 설정하는 데 문제가 있습니다. MapView viewcontroller에서 다른 뷰 컨트롤러의 배열을 가져 오는 함수가 있고 유형에 따라 맵보기에 다른 핀 색상이 필요합니다. 이 switch 문 내에서 주석에 핀 색상 정보를 어떻게 추가 할 수 있는지 잘 모르겠습니다. 주석에 대한 이해는 다소 약해서 솔루션 자체보다는 모든 설명이 크게 감사하게 생각합니다.Swift 3.0 MapView의 주석 핀 색상 설정

class ColorPointAnnotation: MKPointAnnotation { 
    var pinColor: UIColor 

    init(pinColor: UIColor) { 
     self.pinColor = pinColor 
     super.init() 
    } 
} 


    func add(newLocation location_one:[String:Any]) { 

    let momentaryLat = (location_one["latitude"] as! NSString).doubleValue 
    let momentaryLong = (location_one["longitude"] as! NSString).doubleValue 

    var annotation = MKPointAnnotation() 

    switch location_one["type"] { 
     case "Tomorrow": 
      print("The pin color is red") 
      annotation = ColorPointAnnotation(pinColor: UIColor.red) 
     case "Next Week": 
      print("The pin color is green") 
      annotation = ColorPointAnnotation(pinColor: UIColor.green) 
     default: 
      print("The pin color is purple") 
      annotation = ColorPointAnnotation(pinColor: UIColor.purpleColor) 
    } 

    annotation.title = location_one["title"] as? String 
    annotation.coordinate = CLLocationCoordinate2D(latitude: momentaryLat as CLLocationDegrees, longitude: momentaryLong as CLLocationDegrees) 


    DispatchQueue.main.async { 
     self.map.addAnnotation(annotation) 
    } 

    self.map.centerCoordinate = annotation.coordinate 

} 


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

    //  if (annotation is MKUserLocation) { 
    //   return nil 
    //  } 

    let identifier = "pinAnnotation" 
    var annotationView = map.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView 


    if annotationView == nil { 
     annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) 
     annotationView?.canShowCallout = true 
     let colorPointAnnotation = annotation as! ColorPointAnnotation 
     annotationView?.pinTintColor = colorPointAnnotation.pinColor 

    } 
    //  else { 
    //   annotationView?.annotation = annotation 
    // 
    //  } 
    //  map.showAnnotations(map.annotations, animated: true) 
    return annotationView 
} 

답변

1

switch 문을 viewForAnnotation 대리자 메서드로 이동해야합니다. 여기에서 핀을 반환 할 때 색상을 사용자 정의하고 반환 할 수 있습니다. 그래서 같이

:

 annotation.pinColor = MKPinAnnotationColorGreen; 

업데이트 답 :

당신은 MKPointAnnotation를 서브 클래스, 및 주석의 종류를 저장하는 속성을 추가 할 수 있습니다.

add 메소드에서 어노테이션을 작성할 때, 이제까지 어떤 유형의 핀이든 그 속성을 설정하십시오.

이제 viewForAnnotation 메소드에서 mapkit은 사용자 유형의 주석을 제공합니다. set 속성을보고 반환 할 색상 핀을 결정하십시오.

코드가 필요한지 알려주세요.

+0

MKPointAnnotation 서브 클래스 추가에 기반하여 읽은 문서를 기반으로 일부 코드를 추가했습니다 (편집 참조). add 메소드에서이 서브 클래스를 어떻게 참조 할 수 있습니까? – Kevin