【问题标题】:How can I make long-press event in MapKit如何在 MapKit 中进行长按事件
【发布时间】:2020-02-24 16:00:33
【问题描述】:

我可以在 MapKit 中进行注释的点击事件,但是如何在 MapKit 中进行注释的长按事件?

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
        let annotation = view.annotation
        let user = (annotation as! PointAnnotation).user
        let me = mainStore.state.profile
        if user === me {
            return
        }
        let vc = ChatVC.storyBoardInstance
        vc.user = user
        self.navigationController?.pushViewController(vc, animated: true)
    }

这是关于点击事件的代码。

【问题讨论】:

标签: swift annotations mapkit


【解决方案1】:

Swift5:在你的 viewDidLoad() 中,

    let lpgr = UILongPressGestureRecognizer(target: self, 
                         action:#selector(self.handleLongPress))
    lpgr.minimumPressDuration = 1
    lpgr.delaysTouchesBegan = true
    lpgr.delegate = self
    self._mapView.addGestureRecognizer(lpgr)

并在您的视图控制器中实现它,

@objc func handleLongPress(gestureRecognizer: UILongPressGestureRecognizer) {
        if gestureRecognizer.state != UIGestureRecognizer.State.ended {
            return
        }
        else if gestureRecognizer.state != UIGestureRecognizer.State.began {

            let touchPoint = gestureRecognizer.location(in: self.mapView)

        let touchMapCoordinate =  self._mapView.convert(touchPoint, toCoordinateFrom: _mapView)
        yourAnnotation.subtitle = "You long pressed here"
        yourAnnotation.coordinate = touchMapCoordinate
        self._mapView.addAnnotation(yourAnnotation)
    }

}

【讨论】:

  • 我在 lpgr.delegate = self 中遇到问题
  • 你能把错误贴在这里吗?您是否将 UIGestureRecognizerDelegate 添加到您的视图控制器?
  • 嗨@Cosmo 我可以看到我现在可以接收带有坐标的touchPoint。那么我应该将该接触点与我的注释进行比较吗?
【解决方案2】:

理论上,您可以在 MapView 中添加一个长按手势识别器,然后在注释的选择方法中检查识别器的状态。例如,如果您希望在手势进行时发生某些事情,您可以检查识别器的状态是否不是 .ended 或 .cancelled。

例如:

if recognizer.state == .ended || recognizer.state == .cancelled || recognizer.state == .failed {
            // this would cover the gesture no longer being in progress
        } else if recognizer.state == .began {
            // handle the gesture beginning
        } 

我总是在情节提要中添加手势识别器,只需将其放到地图上,然后创建出口/动作。如果您想以编程方式执行此操作,可以阅读更多 here

【讨论】:

  • 好吧,你能上传一些代码示例吗?谢谢
猜你喜欢
  • 1970-01-01
  • 2018-11-27
  • 1970-01-01
  • 1970-01-01
  • 2017-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
相关资源
最近更新 更多