【问题标题】:Update MKPointAnnotation object while dragging拖动时更新 MKPointAnnotation 对象
【发布时间】:2016-08-04 08:26:40
【问题描述】:

我想知道如何在拖动时更新我的​​ annotation 标题,因为所有 annotation 属性都仅限于 get

我尝试过的代码:

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {

    switch (newState) {
    case .starting:
        //view.dragState = .dragging
        print("dragging.....")
    case .ending, .canceling:
        // view.dragState = .none
        let lat = view.annotation?.coordinate.latitude
        let long = view.annotation?.coordinate.longitude
        let coordinates = CLLocationCoordinate2D(latitude: lat!, longitude: long!)
        print(" pin lat \(lat) long \(long)")

        //Error here - title is get only property
        view.annotation?.title = "New Location"

    default: break
    }

}

【问题讨论】:

    标签: ios swift2 mapkit swift3 mapkitannotation


    【解决方案1】:

    MKMapViewDelegate的拖动方法中,注解是只读的,所以你可以使用MKMapViewDelegatedidSelectAnnotationView方法,因为在拖动之前它会调用didSelectAnnotationView方法,为此声明一个selectedAnnotation类型的实例属性MKPointAnnotation.

    var selectedAnnotation: MKPointAnnotation?
    

    现在在didSelectAnnotationView 方法中使用这个属性。

    func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
        selectedAnnotation = view.annotation as? MKPointAnnotation
    }
    

    现在要更改标题,请使用此注释

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
        switch (newState) {
            case .starting:
                //view.dragState = .dragging
                print("dragging.....")
            case .ending, .canceling:
                // view.dragState = .none
                let lat = view.annotation?.coordinate.latitude
                let long = view.annotation?.coordinate.longitude
                let coordinates = CLLocationCoordinate2D(latitude: lat!, longitude: long!)
                print(" pin lat \(lat) long \(long)")
                self. selectedAnnotation?.title = "New Location"
            default: break
        }
    
    }
    

    【讨论】:

    • 欢迎朋友,快乐编码:)
    猜你喜欢
    • 1970-01-01
    • 2012-03-31
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 2012-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多