0

我在地图上显示自定义注释并且很难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”。

我也尝试设置isUserInteractionEnabledTestAnnotationView但没有帮助。我错过了什么?

我通过 cocoapods 安装 Mapbox (5.9.0):

pod 'Mapbox-iOS-SDK', '~> 5.9'
4

1 回答 1

0

我倾向于使用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委托方法。

于 2020-06-11T08:59:12.250 回答