繁体   English   中英

如何将自定义属性从Mapbox注释传递到其标注视图?

[英]How do I pass in custom properties from Mapbox annotation to its callout view?

我将MGLAnnotation子类MGLAnnotation添加额外的属性var tags如下所示:

class MasterMapAnnotation: NSObject, MGLAnnotation {

    var coordinate: CLLocationCoordinate2D
    var title: String?
    var subtitle: String?
    var tags: String?

    init(coordinate: CLLocationCoordinate2D, title: String?, subtitle: String?, tags: String?) {

        self.coordinate = coordinate
        self.title = title
        self.subtitle = subtitle
        self.tags = tags

    }

}


这是传入地图的注释:

let annotation = MasterMapAnnotation(coordinate: CLLocationCoordinate2D(latitude: 50.0, longitude: 50.0), title: "Numero Uno", subtitle: "Numero Uno subtitle", tags: "#tag1 #tag2")
mapView.addAnnotation(annotation)


mapView委托调用自定义标注视图:

func mapView(_ mapView: MGLMapView, calloutViewFor annotation: MGLAnnotation) -> MGLCalloutView? {

    return MasterMapCalloutView(representedObject: annotation)

}


所以在callout视图子类(下面)中,如何访问这个新的属性tags

class MasterMapCalloutView: UIView, MGLCalloutView {

    var representedObject: MGLAnnotation
    let dismissesAutomatically: Bool = false
    let isAnchoredToAnnotation: Bool = true
    lazy var leftAccessoryView = UIView()
    lazy var rightAccessoryView = UIView()
    weak var delegate: MGLCalloutViewDelegate?

    required init(representedObject: MGLAnnotation) {
        self.representedObject = representedObject
        super.init(frame: .zero)
    }

    required init?(coder decoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // callout view delegate: present callout
    func presentCallout(from rect: CGRect, in view: UIView, constrainedTo constrainedView: UIView, animated: Bool) {

        if !representedObject.responds(to: #selector(getter: MGLAnnotation.title)) {
            return
        }

        view.addSubview(self)

        let title = representedObject.title
        let tags = representedObject.tags // how to access this?

    }

}


问题显然是子类( MasterMapAnnotation )拥有自定义tags属性,而不是它的超类( MGLAnnotation ),但我不知道如何(a)将representObject设置为MasterMapAnnotation或(b)只是访问MasterMapAnnotation自定义属性而不重新配置协议。

我可能会遗漏一些东西,但你肯定只是检查是否可以将MGLAnnotation对象强制转换为MasterMapAnnotation:

guard let masterAnnotation : MasterMapAnnotation = representedObject as? MasterMapAnnotation else { return }

let tags : String? = masterAnnotation.tags

// etc

显然除了使用后卫之外还有其他方法来控制流量,但我希望你能得到主旨。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM