2017-05-17 9 views
0

マップアノテーションのピンの色を設定できません。 MapViewのViewControllerに、別のView Controllerから配列を取得する関数があります。この型の場合によっては、マップビューに異なるピンカラーが必要です。私はどのように私はこのスイッチステートメント内の注釈にピンの色情報を追加することができますか分からない。注釈の私の理解はかなり弱いので、解答そのものではなく、説明は非常に高く評価されます。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

関連する問題