如果添加新的自定义批注,然后单击按钮以弹出标注,或单击地图上的任意位置,则不会发生任何事情。如果再次单击,一切正常...有任何想法吗?我看过很多理论,但到目前为止还没有运气...
@IBOutlet weak var mapView: MKMapView!
// In ViewDidLoad, I define my LongPressGestureRecognizer
let uilpgr = UILongPressGestureRecognizer(target: self, action: #selector(createNewAnnotation))
uilpgr.minimumPressDuration = 0.25
mapView.addGestureRecognizer(uilpgr)
// And here is the selector:
@objc func createNewAnnotation(_ sender: UIGestureRecognizer) {
let touchPoint = sender.location(in: self.mapView)
let coordinates = mapView.convert(touchPoint, toCoordinateFrom: self.mapView)
let heldPoint = MKPointAnnotation()
heldPoint.coordinate = coordinates
if (sender.state == .began) {
heldPoint.title = "Set Point"
heldPoint.subtitle = String(format: "%.4f", coordinates.latitude) + "," + String(format: "%.4f", coordinates.longitude)
mapView.addAnnotation(heldPoint)
}
}
如果我用拍子识别器代替长按,则会显示标注,但拍子会创建另一个注释...因此长按必须是正确的方法。但是我该如何解决这个问题,以便用户可以长按创建注释,然后点击一次以获取标注?
所以,我经过整整三天的努力终于找到了解决方案……发生的事情是长按继续遮盖了所有其他手势。因此,不能识别下一个拍子,只有第二个拍子。修复非常简单,可以在选择器中进行如下修复:
@objc func createNewAnnotation(_ sender: UIGestureRecognizer) {
let touchPoint = sender.location(in: self.mapView)
let coordinates = mapView.convert(touchPoint, toCoordinateFrom: self.mapView)
let heldPoint = MKPointAnnotation()
heldPoint.coordinate = coordinates
if (sender.state == .began) {
heldPoint.title = "Set Point"
heldPoint.subtitle = String(format: "%.4f", coordinates.latitude) + "," + String(format: "%.4f", coordinates.longitude)
mapView.addAnnotation(heldPoint)
}
// Cancel the long press gesture!
sender.state = .cancelled
}
通过这种微小的更改,LongPress消失了,而水龙头由地图和注释处理。