我在地图上显示自定义注释,并且很难在我的代理上接收didSelect
调用。下面是ViewController的代码:
class TestAnnotationClickViewController: UIViewController, MGLMapViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let mapView = MGLMapView(frame: view.bounds)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.delegate = self
mapView.addAnnotation(TestAnnotation())
view.addSubview(mapView)
}
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
if annotation is TestAnnotation {
let view = TestAnnotationView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
return view
}
return nil
}
func mapView(_ mapView: MGLMapView, didSelect annotation: MGLAnnotation) {
print("annotation didSelect")
}
func mapView(_ mapView: MGLMapView, didSelect annotationView: MGLAnnotationView) {
print("annotation view didSelect")
}
}
以下是注释类和相应视图的代码:
class TestAnnotation: NSObject, MGLAnnotation {
var coordinate: CLLocationCoordinate2D
override init() {
coordinate = CLLocationCoordinate2D(latitude: 33.9415889, longitude: -118.4107187)
}
}
class TestAnnotationView: MGLAnnotationView {
required init?(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
private func setupView() {
backgroundColor = .green
}
}
当我按下注解(绿色矩形)时,我希望调用委托方法didSelect
。但是,它们都不会被调用。而且控制台不会打印"annotation didSelect“或"annotation view didSelect”。
我也尝试在TestAnnotationView
上设置isUserInteractionEnabled
,但没有帮助。我遗漏了什么?
我通过cocoapods安装Mapbox (5.9.0):
pod 'Mapbox-iOS-SDK', '~> 5.9'
发布于 2020-06-11 08:59:12
我倾向于使用reuseIdentifiers来创建注释,并构造一个init
来承载该注释和annotation
,因此对于您的用例,如下所示:
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
if annotation is TestAnnotation {
let view = TestAnnotationView(reuseIdentifier: "test", frame: CGRect(x: 0, y: 0, width: 100, height: 100), annotation: annotation)
return view
}
return nil
}
在添加初始化器的TestAnnotationViewClass
中:
init(reuseIdentifier: String?, frame: CGRect, annotation: MGLAnnotation) {
super.init(reuseIdentifier: reuseIdentifier)
self.frame = frame
setupView()
}
确保所有内容都已设置好,以便注释可以响应触摸并触发didSelect
委托方法。
https://stackoverflow.com/questions/62311467
复制