i子分类 MGLAnnotation
添加额外的属性 var tags
so:
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)
}
因此,在"标注"视图子类(下图)中,如何访问此新属性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)将ArdectedObject设置为MasterMapAnnotation
或(b)简单地访问MasterMapAnnotation
自定义属性重新配置协议。
我可能缺少某些东西,但是您肯定会检查是否可以将MGlannotation对象施放为Mastermapannotation:
guard let masterAnnotation : MasterMapAnnotation = representedObject as? MasterMapAnnotation else { return }
let tags : String? = masterAnnotation.tags
// etc
显然,除使用警卫以外,还有其他控制流程的方法,但我希望您能得到要点。