2017-01-24 7 views
0

私はmapkitに2つのピンを持っています、両方とも同じ注釈ビューの下にありますので、両方のピンが同じ色です。どのようにピンを異なる色にすることができますか?私はこんにちはが赤で、こんにちはは青くなりたいです。同じannotationview(swift3)の下でmapkitのピンの色を変更する方法

import UIKit 
import MapKit 

class ViewController: UIViewController, MKMapViewDelegate { 

@IBOutlet var jmap: MKMapView! 

override func viewDidLoad() { 
    jmap.delegate = self; 
    let hello = MKPointAnnotation() 
    hello.coordinate = CLLocationCoordinate2D(latitude: 40, longitude: -73) 
    jmap.addAnnotation(hello) 
    let hellox = MKPointAnnotation() 
    hellox.coordinate = CLLocationCoordinate2D(latitude: 34, longitude: -72) 
    jmap.addAnnotation(hellox) 
} 

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { 
    let annotationView = MKPinAnnotationView() 
    annotationView.pinTintColor = .blue 
    return annotationView 
}} 

答えて

4

などpinTintColorとして、あなたが望む任意のカスタムプロパティを追加するサブクラスMKPointAnnotation

class MyPointAnnotation : MKPointAnnotation { 
    var pinTintColor: UIColor? 
} 

class ViewController: UIViewController, MKMapViewDelegate { 
    @IBOutlet var jmap: MKMapView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     jmap.delegate = self 

     let hello = MyPointAnnotation() 
     hello.coordinate = CLLocationCoordinate2D(latitude: 40, longitude: -73) 
     hello.pinTintColor = .red 

     let hellox = MyPointAnnotation() 
     hellox.coordinate = CLLocationCoordinate2D(latitude: 34, longitude: -72) 
     hellox.pinTintColor = .blue 

     jmap.addAnnotation(hello) 
     jmap.addAnnotation(hellox) 
    } 

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { 
     var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "myAnnotation") as? MKPinAnnotationView 

     if annotationView == nil { 
      annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myAnnotation") 
     } else { 
      annotationView?.annotation = annotation 
     } 

     if let annotation = annotation as? MyPointAnnotation { 
      annotationView?.pinTintColor = annotation.pinTintColor 
     } 

     return annotationView 
    } 
} 
関連する問題