【问题标题】:how to change pin color in mapkit under the same annotationview (swift3)如何在同一注释视图下更改 mapkit 中的引脚颜色(swift 3)
【发布时间】:2017-01-24 04:19:33
【问题描述】:

我在 mapkit 中有 2 个图钉,它们都在同一个注释视图下,所以这两个图钉的颜色相同。我怎样才能使别针有不同的颜色。我希望 hello 是红色的,而 hellox 是蓝色的。

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
}}

【问题讨论】:

    标签: ios swift swift3 mapkit mkannotationview


    【解决方案1】:

    子类MKPointAnnotation 添加您想要的任何自定义属性,例如pinTintColor

    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
        }
    }
    

    【讨论】:

    • 如何在操场上做到这一点? mapView(_:viewFor:) 会在哪里?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多