我有一个带注释的MKMapView。我的目标是在地图完成滚动时隐藏注释(如果选择了一个注释)。
调用注释时,我将注释分配给变量以跟踪它。
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
lastSelectedAnnotation = view.annotation
}
我知道:
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool){ }
但是,我无法弄清楚(这里是初学者),如何检测地图已完成更改其区域,以便我可以调用我的函数:
func hideSelectedAnnotation(_ mapView: MKMapView) {
DispatchQueue.main.async {
mapView.deselectAnnotation(self.lastSelectedAnnotation, animated: true)
self.lastSelectedAnnotation = nil
}
}
当点击附件按钮时,我也会隐藏注释:
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl){
hideSelectedAnnotation(mapView)}
我已经尝试保存区域的坐标,并将它们与地图进行比较,但地图并不是必须使注释居中。我也可以启动一个计时器,当不再调用regionDidChangeAnimated时隐藏注释。但接缝就像屠杀它一样。
谢谢你的帮助!
我想你已经弄清楚了......
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool){
// Call your function here
}
每次地图视图区域更改时都应该触发(除非用户的手指发生了更改)
-----编辑-----
不幸的是,您必须使用UIPanGestureRecognizer检测用户输入。
我成功地使用了一个UIPanGestureRecognizer,如下所示:
lazy var mapPanGestureRecognizer: UIPanGestureRecognizer = {
let gr = UIPanGestureRecognizer(target: self, action: #selector(draggedMap))
gr.delegate = self
return gr
}()
您还必须将UIPanGestureRecognizer添加到地图中
yourMap.addGestureRecognizer(mapPanGestureRecognizer)
然后,您可以通过检查手势的状态来管理#selector函数中发生的事情,就像这样
@objc func draggedMap(panGestureRecognizer: UIPanGestureRecognizer) {
// Check to see the state of the passed panGestureRocognizer
if panGestureRecognizer.state == UIGestureRecognizer.State.began {
// Do something
}
}
状态允许您确定用户是否结束了手势,是在手势的中间还是开始手势。 List of possible states